Nebex Elias
Nebex Elias

Reputation: 432

Where to store JWT token in angular?

I am building an app with Django and angular. Currently, I am storing a JWT issued by the backend on local storage. But, I am concerned about XSS attacks. Should I store the token using HTTP only cookie? I am also thinking of storing the token in my auth service class in a variable field. But I am not entirely sure if angular shares the service across the entire app. Will there be a single instance of my auth service?

Upvotes: 9

Views: 22043

Answers (3)

Yassin Mo
Yassin Mo

Reputation: 610

There are 3 ways to store authentication tokens in Angular apps

1- In-memory storage: In this technique, a token is stored in the application page itself, but it is lost on page refresh and must be retrieved again.

2- HTML5 web storage (local storage and session storage): In this technique, data is stored in browser storage. Data stored this way is accessible by all tabs in the same browser within the same domain.

Session storage:: Data stored in the session expires once the browser is closed.

Local storage: Data stored in local storage doesn’t expire until we clear the data from the browser.

3- HttpOnly cookie: In this technique, a token is stored in cookies. Data stored this way can be accessed by the server. The browser automatically appends a cookie in requests sent to the server.

For additional security, we must consider a few more things on the server side, such as:

  1. Token expiration validation.
  2. Content security policy.
  3. Refresh token mechanism.
  4. Anti-forgery token mechanism.

Upvotes: 0

Stavm
Stavm

Reputation: 8131

Let get things straight:

If you got XSS'd - it's game over. period.

That said,

one approach that passed external Penetration Tests in my current workplace would be placing JWT token in an httpOnly secure samesite=strict cookie.

To further prevent CSRF you can add an identifier in the web storage, attach it to every xhr as a header.

In the server, extract the identifier from the jwt and compare it with the header value.

Upvotes: 0

ne1410s
ne1410s

Reputation: 7102

Assuming you are using standard dependency injection, a new instance of your service is instantiated each time, so therefore a field in the service class will not be stored.

Session or local storage is fine though. The JWT mechanism prevents the contents from being altered easily by a client (as you must be verifying it on your downstream backend services).

Conceivably you could retain some original request signature in the JWT payload, and check any secondary requests under this match the same. For example, IP address, user agent string etc.

Personally (provided it is implemented correctly), I consider this more than enough security for the majority of web facing applications. Obviously banking / finance apps may wish to go the extra mile, with 2 factor authentication, etc.

Upvotes: 4

Related Questions