Integrate your SPA with the Token Handler
On this page
After token handler components are Integrated with the API Gateway the SPA can send requests to public token handler endpoints. The SPA integration is then a low code task, since the backend endpoints implement the main OAuth and cookie work for the SPA. The SPA can use any web static content host and uses lightweight fetch requests to implement a code flow and call APIs.
Run a Code Flow
You can use the Token Handler JS Assistant to interact with the OAuth Agent, which also provides type definitions for API requests and responses. Add the library to your project and initialize it (see the README). Then, construct an OAuthAgentClient
object when your application starts:
const oauthClient = new OAuthAgentClient({oauthAgentBaseUrl: 'http://api.demoapp.example/apps/example'});
To implement a login, call the /login/start endpoint of the OAuth Agent to get the authorization request URL. Then redirect the browser to that URL. The following example redirects the whole window to the authorization server
const response = await oauthClient.startLogin();location.href = response.authorizationUrl;
Whenever the SPA loads it can ask the OAuth Agent to process the page load event. If the SPA's current URL contains an authorization response, the OAuth Agent processes it, gets tokens and encrypts the tokens into HTTP-only cookies. For any page load, the session response contains the user's authentication status and, for authenticated users, the ID token claims. If applicable, the session response also sets the cookies with the encrypted tokens.
this.sessionResponse = await oauthClient!.onPageLoad(location.href);
Call APIs
To call APIs, use your preferred fetch library and opt into sending cookies using an option like credentials: include. The browser then sends a cookie that contains the access token to the API gateway, where the OAuth Proxy decrypts it and forwards the access token to the upstream API. The following code shows an example on how to call APIs from the SPA via the OAuth Proxy of the token handler.
const init = {mode: 'cors',credentials: 'include',method: 'GET',headers: {'token-handler-version': '1',},};const response = await window.fetch(`${tokenHandlerBaseUrl}${path}`, init);
Web Specific Security
The token handler components implement standard web protections, to deal with Cross Site Request Forgery (CSRF) and Cross Origin Request sharing (CORS) concerns. Therefore, APIs only need to process JWT access tokens.
Summary
At this point there is a working SPA that uses OAuth and cookie security, with no tokens in the browser. For further useful token handler resources and more detailed tutorials, see the Token Handler Summary.
Join our Newsletter
Get the latest on identity management, API Security and authentication straight to your inbox.
Start Free Trial
Try the Curity Identity Server for Free. Get up and running in 10 minutes.
Start Free Trial