Standard Token Handler

Standard Token Handler

Overview

The role of the main token handler API (the OAuth agent in the below diagram) is to handle the OpenID Connect flow for Single Page Applications (SPA). This includes issuing of secure cookies for the browser and managing follow-on operations for token refresh, retrieving user info and signing out:

Token Handler

This implementation is coded in Node.js and implements the Authorization Code Flow with PKCE using a client secret. The result is that only the strongest HTTP Only, SameSite=strict cookies are used in the browser, while JWT access tokens are used in a standard way by APIs.

Token Handler Operations

The following operations represent the Token Handler’s API interface, and all of these are designed to serve SPAs via Ajax requests from the browser. This enables the SPA to fully control behavior such as when redirects occur:

EndpointDescription
POST /login/startStart a login by providing the request URL to the SPA and setting temporary cookies
POST /login/endValidate the request, complete the login and return HTTP only encrypted cookies to the browser
GET /userInfoReturn Personally Identifiable Information (PII), such as the user name, to the SPA
POST /refreshAsk the token handler to refresh the current access token and rewrite secure cookies
POST /logoutAsk the token handler to clear secure cookies and return an end session request URL

A token handler is a tricky API to develop, since its main focus is on browser and OAuth infrastructure:

BehaviorDescription
Authorization CodesThe API needs to receive real authorization codes in order to get tokens
HTTP RedirectsThe SPA client therefore needs to perform real HTTP redirects and user logins
Cross Origin RequestsThe API and its SPA client must both deal with Cross Origin Request Sharing (CORS)
CookiesThe API operations need to frequently read, write and update encrypted cookies containing tokens

API Driven Development

When working on the token handler as an API it is useful to initially avoid a browser and use a test driven approach. In the following sections we will show how to do this for the token handler API. First get the code, which contains the following resources:

Token Handler Resources

Prerequisites

Next ensure that the following components are installed:

You will also need a license file for the Curity Identity Server. If you do not have one you can get a free community license from the Curity Developer Portal by signing in with your GitHub account.

URLs

When running on a development computer, the token handler is configured to use the following base URLs. The default setup uses plain HTTP URLs in order to simplify infrastructure on a development computer, though of course the token handler should be updated to use SSL for deployed environments:

ComponentBase URL
Token Handlerhttp://api.example.local:8080/tokenhandler
Curity Identity Server Endpointshttp://login.example.local:8443
Curity Identity Server Admin UIhttps://localhost:6749/admin

For URLs to work you will need to add the following entries to the local computer’s hosts file:

127.0.0.1  api.example.local login.example.local
:1 localhost

Run the Token Handler API

This is done in the standard Node.js manner, after which the API’s HTTP endpoints are available for a client to call:

npm install
npm start

You can then simulate a request from the SPA via the following test command, to ensure that connectivity is working:

curl -X POST http://api.example.local:8080/tokenhandler/login/start \
-H "origin: http://www.example.local" | jq

Token Handler Security Code

The OAuth logic for the token handler API can be studied and adapted if needed. The controller source files provide an outline of processing, including cookie issuing. To understand the main interaction with the Authorization Server, see the authorizeUrl and getToken modules:

Standard Logic

Run the Authorization Server

This is done by first copying a license file into the test/idsvr folder and then running the following commands, which will spin up the Curity Identity Server in a Docker container:

cd test/idsvr
./deploy.sh

You can then log in to the Admin UI with credentials admin / Password1 to view client configuration details. OAuth requests on behalf of the SPA are initiated from the token handler, which uses a client secret when it calls the Authorization Server:

The token handler uses the registered SPA client’s OAuth settings, and these include a string client secret for requests from the token handler to the Authorization Server:

Standard Secret

Run an API Test Client

During token handler development it can be useful to use a test client that sends the same HTTP requests as an SPA, but avoids the need to continually switch to a browser and extract values such as authorization codes. Curity have provided a script based client using the popular curl and jq tools, and it is run via the following commands:

cd test
./test-token-handler.sh

The script runs a complete SPA workflow, using a preconfigured user account shipped with the Docker deployment. This begins with a login, then continues with refresh and user info requests, finishing with a logout. This fast feedback will enable any coding bugs in the token handler to be quickly found and ironed out:

Base Token Handler Workflow

OpenID Connect Messages

The token handler returns front channel request URLs to the SPA, which then updates the browser location to this URL, to begin the user authentication process. At this point, the token handler has also written a temporary secure cookie containing state and code_verifier values.

GET http://login.example.local:8443/oauth/v2/oauth-authorize
    ?client_id=spa-client
    &redirect_uri=http%3A%2F%2Fwww.example.com%2F
    &response_type=code
    &code_challenge=k2XFDLJ_mIVEt25-phu4_3O4Jqrd8QqTGGbeEsql3Rc
    &code_challenge_method=S256
    &state=NlAoISfdL1DxPdNGFBljlVuB1GDjgGARmqDcxtHhV8iKNYu6ECS2KOavDHpI3eLN
    &scope=openid%20profile

When authentication completes, the SPA sends the token handler the response URL containing the authorization code. The token handler then validates the response using the temporary cookie, then sends a back channel request to the Authorization Server, along with a client secret:

POST http://login.example.local:8443/oauth/v2/oauth-token

grant_type=authorization_code&
client_id=spa-client&
client_secret=Password1&
authorization_code=bMYnHhHHRFRnT7sbuPmqIzHpb8RFfqtg&
redirect_uri=http://www.example.com/

Tokens returned in the response are then stored in HTTP Only encrypted secure cookies that are returned to the browser but not accessible from Javascript code. AES256 symmetric encryption is used to encrypt the cookies, with a key only known to the token handler.

Browser Integration

Once the API is working as expected and any code changes have been completed, you can then deploy it and test with real SPAs running in the browser. This is simply a case of pointing the SPA to the base URL of the token handler in the deployed environment:

{
    "businessApiBaseUrl": "https://api.example.com/api",
    "oauth": {
        "tokenHandlerBaseUrl": "https://api.example.com/tokenhandler"
    }
}

See the following articles for further details on running a fully integrated solution:

ArticleDescription
SPA Code ExampleAn end-to-end setup for a development computer, to run an example SPA that uses this token handler
End-to-End TutorialFurther details on the end-to-end setup, including deployment and infrastructure

Conclusion

A token handler is a tricky component to develop, so Curity have provided a reference implementation that can be simply plugged in. If required companies can adapt Curity’s token handler implementation for their own purposes, by following the API development steps in this tutorial.