Use JWT token for authentication


I have a Data Abstract service implemented in Delphi which must be authenticated using a JWT Token.
Normally, I would expect this to be done through the OnHTTPAuthentication event.

But there is a catch:
The server must also issue the JWT token through the login call.
That means that the login call must be allowed to pass without JWT Token, and all other calls must only be allowed when the JWT Token is valid.

However, when the OnHTTPAuthentication event is triggered, it is not yet known which call is going to be executed. So this event is unable to decide whether a JWT token is required or not.

At this point the Session ID token is also unavailable, since it is encoded in the message.
So I am not able to flag the RO-Generated session as authenticated or not.
Manually creating/destroying a session is also not an option, since I see no way to pass on the new session ID to the further processing of the message.

How can I solve this ?

An additional issue is that the OnHTTPAuthentication event parses the authentication header in username/password, which is of course not correct for a bearer token. This can be worked around, since the http request instance is passed to the event, but this is not very elegant. Maybe a separate class to handle could be created ?

Any insights are appreciated!


this event supports only basic authorization.

I can suggest to use HTTPServer.OnCustomResponseEvent .

this event is designed for processing unknown requests. You can remove all dispatchers so all requests will be handled by this event.
in this event you can parse incoming request (headers & data) for JWT token and generate response (headers & data).

see more at Using OnCustomResponseEvent in a ROSDK Server snippet or related topics.

if you are looking for HTTPAPI autorization, you may look at uROHttpApiSimpleAuthenticationManager.pas - it demonstrates bearer authentication

I will try this.
Thank you for the suggestion!

I tried your the OnCustomResponse event to implement authentication with a JWT Token.
This part works.

The JWT token contains the user ID. How can I pass this user ID on to the rest of the API ?
It seems I can’t use the session, since the session ID is passed in the message, which is only streamed inside the MainProcessMessage() call.

Currently the only way I see is create a descendent of the message, to override initializeread to capture the token, and override ReadFromStream to apply the user ID to the session after the message was read.

But maybe there is a simpler way ?


You can read message manually like

      (Message as IROMessage).ReadFromStream(lStream);