Web Connection
JSON REST API return values upon failed validation
Gravatar is a globally recognized avatar based on your email address. JSON REST API return values upon failed validation
  Derek
  All
  Nov 15, 2018 @ 11:39am

I'm hoping someone can help me here.

I have an angular 6 app that is making AJAX calls to a west wind JSON REST service. I've implemented a token validation that is checked in OnProcessInit(). When the token validation fails I am forced to RETURN .f. from OnProcessInit. This results in a non-JSON object being returned to my app, which usually excepts a JSON string upon a successful validation.

I would like to properly handle incorrect or expired tokens in my app. This will require a proper JSON string being returned. Is there something I'm overlooking in the process?

Any help anyone can offer is greatly appreciated!

Gravatar is a globally recognized avatar based on your email address. re: JSON REST API return values upon failed validation
  Rick Strahl
  Derek
  Nov 15, 2018 @ 03:07pm

Hi Derek,

If you RETURN .F. from OnProcessInit() you have to generate your own response. You're probably comparing against what Process.Authenticate() does, but that method internally creates an HTML response and that's what generates the output and redirection to the login page.

In your own code that wants to do global checks you have to generate the HTTP response, which should be easy for an auth failure.

Ideally what you'll want to do is:

FUNCTION OnProcessInit()

* ... other stuff

IF !THIS.ValidateToken()  && whatever you do to validate your token
    THIS.oResponse.Status = "401 Unauthorized"
    THIS.oResponse.ContentType = "application/json"
    THIS.oResponse.Write([{ "isError": true, "message": "Your login has expired" }])
    RETURN .F.
ENDIF

RETURN .T.
ENDFUNC

The proper response to an auth failure is a 401 response which in an HTML application will prompt you for authentication. In your Angular app your client probably should have a Route Guard or HTTP Interceptor to check for 401 responses and then redirect back to the login route.

+++ Rick ---

© 1996-2018