How to store user data to enable automatic signing to my angular app?

Viewed 613

I have an angular application and I want to add functionality that stores user credentials in the browser so that when they leave the site and come back, they are automatically logged into their homepage. I am thinking to store the username and apitoken as cookies. And then retrieve those whenever somebody visits the homepage (if they exist). And then send those to the server to automatically log in the user. But I am wondering is this a good way to do it? Is this secure? If not could somebody explain a better way to do it and/or provide some resources for me to read how to do it? Thanks!

1 Answers

As you mentioned in the comments, you are using an API token (similar to JWT) for authentication. With that, you have basically two options to locally persist the token (=session):

The advantage of LocalStorage is, that it's easy to handle and your application can always access the payload of the JWT, e.g. when it expires or what routes should be accessible. The problem is, that LocalStorage is vulnerable to XSS (Cross-Site-Scripting) attacks, meaning that someone else can access its contents and therewith steal the session.

A more secure alternative are HTTP-only cookies (set flags Secure and HttpOnly). Those cookies are not accessible via JavaScript and hence cannot be stolen via XSS attacks. The drawback is apparent: You cannot access the token's contents from your app.

In general, your api tokens should only be valid for a very short time. If you want to give your users the possibility to stay logged in, you should use refresh tokens. These are valid for a longer period and allow for acquiring a new api token without logging in. The advantage here is, that the refresh token is not stateless and can be revoked.

Which solution suits you the best depends on your security requirements.

Related