Angular 2/4 where to store token

user2870934 picture user2870934 · Sep 19, 2017 · Viewed 20.5k times · Source

I have a rest api for generating token, which i'm using in angular 4 client side, but the question is where to store this token.

In the internet i found that i can store in local storage or in the cookie.

So my question is, if store token is the local storage for example, and i have just copied the valid token from another browser, then i will have a valid token, so there is any security of storing token like that, and basically the same with cookies, or maybe i missed some important information?

Answer

Alex Beugnet picture Alex Beugnet · Sep 19, 2017

Here is a complete article about Tokens / Cookies that can give you a lot of knowledge about this subject : auth0 : Cookies VS Tokens

I'll quote the most important parts to make you understand what's coming next :

Two of the most common attack vectors facing websites are Cross Site Scripting (XSS) and Cross Site Request Forgery (XSRF or CSRF).

Cross Site Scripting) attacks occur when an outside entity is able to execute code within your website or app.

Cross Site Request Forgery attacks are not an issue if you are using JWT with local storage. On the other hand, if your use case requires you to store the JWT in a cookie, you will need to protect against XSRF.

Our CTO has argued in the past that XSS attacks are much easier to deal with compared to XSRF attacks because they are generally better understood.

So basically to sum up :

Hence, I'd recommend a standard JWT Token approach to manage your token. Since your token is signed with the JWT format, this is the safest solution in my opinion. Of course, a standard token would need to be either encrypted or signed (not the same) to be really secure.

Really easy to set up and manages with appropriate libraries (such as https://github.com/auth0/angular2-jwt)


To go further : I imagine your token would be used for authentication, and be aware that people have already worked with that and know what is good / bad practice using them.

You should take a look at how authentications are managed from working websites (such as Twitter / Facebook, etc...) where they use Refresh Tokens. Here are some additionnal links that could interest you :


EDIT : Additionnal links about best practices with JWT :