I created an api that sends a user "access token" and "refresh token" in order to use them for authentication and refresh the access token.
I'm using Angular on client side , the problem I have there is a lot of discussion and ways to store those tokens like localstorage, sessionStorage and Cookie.
Which one should I use , because each time I google I find they have downside for example I see CSRF and XSS attacks , and cookie aren't restful etc.
The idea I have is : Store access token , when I get "401" error I use refresh token to get a new access token both of them I think storing them in SessionStorage.
Or should I use a long lived access token that expire after a long time?
Kareem
Do you want the token to be available in more than one browser tab? If so, localstorage or cookies is the way to go. If you want to limit access to a single tab, then sessionstorage is the way to go.
Security is a whole other matter. One is not necessarily more secure than the other. There are some arguments that local/session storage can be less secure than cookies if HttpOnly is used on the cookies since then it can't be read by JavaScript, so it can't be accessed by a client-side script without going through some unorthodox measures, whereas local/session storage are designed to be read by JavaScript.
The question to ask is: if an unauthorized person gets the access token, how would you prevent them from using it? It's a valid token, right? Seems like you'd need more than just the access token alone. This is the problem security experts have been dealing with for a very long time, and very elaborate schemes exist to make things more secure. How far do you go, though? The answer to that depends on what it is you're protecting. Financial and health data, for example, are things you take extra measures to secure.
I think that will be a highly opinionated answer.
If your API is consumed by third party applications, using cookies is not an option (well, it is, but you don’t want to make the lif of other devs harder.)
If your API is consumed only by your own front-end, you can go with whatever unorthodox method you want. If you otherwise use the local or session storage, even that is fine. It can even be a global(ish) variable in the application.
You may want to take a look at riot.im or vector.im, it may give you some ideas.
TheSheriff
Co-Founder, Founder, Entrepreneur & Problem Solver
Store is as a cookie. Localstorage and sessionstorage should be used for things like caching files etc. I.e. anything that's large. Where as cookies are used to store "small" sets of info, such as access/session tokens.