I have an Angular Application where I am using Keycloak (OAuth2 provider) Login Page. Once I login with username and password in the Login page, I am getting auth code and with that code I am calling Keycloak Token Generator API http://localhost:8080/realms/CloudBrokerRealm/protocol/openid-connect/token
and getting access token & refresh token successfully. No issues till getting the tokens.
Now I need to store the access & refresh tokens in Client side so that I can send the bearer access token in Authorization Header for calling my backend Rest APIs (Resource APIs created with Java, Spring Boot, Spring Security).
After searching many links on internet I can see some people are suggesting to store token in httpOnly cookie intead of local storage or session storage on browser. But I am not able to store the tokens in httpOnly cookie as Keycloak sends the tokens in Response Body, not as cookie when calling Keycloak Token Generator API mentioned above. I can't set the cookie (httpOnly) from javascript / angular after extracting the tokens from response body as it is not possible.
So my questions are:
- How to store the OAuth2 access & refresh token in Client side which will be required to call some backend Rest APIs (Resource APIs) with Bearer Token as 'Authorization' header.
- If we store it in httpOnly cookie, how we will send the Token as 'Authorization' header as our Rest API will expect that mandatory header.
CodePudding user response:
Current best practices are described in OAuth 2.0 for Browser Based Apps. Section 6.2 describes how cookie to token translation is usually done, via a backend for frontend.
Tokens cannot be stored fully securely in the browser. The perception is likely to be that an app using tokens in Javascript has greater security concerns, eg ways to intercept and exfiltrate them.
A cookie implementation for SPAs usually involves an API gateway that manages translating between cookies and tokens. It is a whole extra deployment layer though, so requires design and planning.
CodePudding user response:
Don't implement authorization code (with PKCE) flow by yourself. Use a certified OIDC client library.
My favorite for Angular is angular-auth-oidc-client.
It will handle
- redirections to authorization-server
- exchange of authorization code for tokens
- silent token refreshing just before it expires
- auto login with Angular route guard
- request Authorization (position access token in requests header) with HTTP interceptor
- ...
All that with just a little conf.