On-demand Authentication

On-demand authentication is mapping a remote authenticated user to an identity in the local system (aka API). If this requirement is not satisfied then the API can respond that the client requires to present a valid authentication token. The API should present the client with options. The creation of a valid token may be then be satisifed elsewhere.

There are so many ways to address this solution. This tutorial uses Auth0 as a provider and demonstrates intercepting 401 Unauthorized responses and then replays with a valid JWT (JSON Web Token).

Note: The current implementation is less than ideal as all devices pop a new window causing potential user confusion. However, it works well enough for demonstration purposes. This code currently suffers from inter-process communication between the windows which is ‘remedied’ with a refresh. Note2: We won’t deal with sliding windows

ondemand authentication

Some general guidelines

  • use a request interceptor to add an ‘Authorization’ header
  • setup a response interceptor on 401 responses and deals with the WWW-Authenticate header and queues for replay
  • use the API to find out what you need for the client to make the authentication attempt (ie configuration isn’t included at compile time)
  • ensure the replayed request now has the updated ‘Authorization’ header

Recap on over-the-wire-protocol

Request Interceptor

The underlying http client is axios and thus wrapped implemented specific to interceptors for that library. It is promised-based and thus translatable to other libraries. In the first request above, you would have already seen the request headers that ask for JSON (Accept header interceptor is covered here)

Repond with login (or silent renew)

Ensure Authentication is reset

Replay request

Unlock the next chapter
When the API responds 401 unauthorized, what else does it provide?
Nothing and you need click login
A URI in the response body
A login form
A WWW-Authenticate header that provides options on how to authenticate