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
WWW-Authenticate
header and queues for replayThe 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)