Spring Security OAuth2 store access_token in cookie

Viewed 1616

I using Spring Security + Angular. When I make post request to /oauth/token and get token:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDY5NDQwODYsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BRE1JTiJdLCJqdGkiOiI4M2VhMTA1MC05NjczLTRlZGItOTlmMS0yNWIzOTQ1ODdjMmUiLCJjbGllbnRfaWQiOiJmcm9udGVuZCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdfQ.i6v2G70eEgGUt_CdgctcTrGgz_RHs6OuEA8lGHOgVro",
    "token_type": "bearer",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhdGkiOiI4M2VhMTA1MC05NjczLTRlZGItOTlmMS0yNWIzOTQ1ODdjMmUiLCJleHAiOjE1NDk1MzI0ODYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiNzQxMDA0NzUtODkxOC00YjM5LTk5NDMtNjAzMWIxMGVjNGQ3IiwiY2xpZW50X2lkIjoiZnJvbnRlbmQifQ.3QOdAL10lQsPSvsFfgyf02gvAanyJ-R1BX_wtF1APB0",
    "expires_in": 3599,
    "scope": "read write",
    "jti": "83ea1050-9673-4edb-99f1-25b394587c2e"
}

How can I on the Spring Security side specify the installation of cookies and save a token there? Or do I have to do it on the Angular side like this:

Cookie.set("access_token", token.access_token, expireDate);

What's the right thing to do? It seems to me that storing a token in cookies is a correct and safe decision.

1 Answers

Access tokens are intended for user agents that perform rest calls. They can securely store the access tokens (most do it in memory on a secure server) and pass that token with each call up to the server.

That being said, your application should not take that token and send it down to the browser in the form of a cookie.

If you are using an implicit_grant then your application is already considered of lesser security because no client credentials were required to fetch the token.

In that scenario, I would recommend holding it in memory in your application. If the application has to store it (to survive reloads etc), consider using local session storage

Worst case scenario local storage will survive browser close.

But I don't think you need cookies here. Because the token is passed to an API using an authorization header with the bearer prefix

Authorization: Bearer AbCdEf123456

Hope this helps

Related