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?
-
1Possible duplicate of [Where to store JWT in browser? How to protect against CSRF?](https://stackoverflow.com/questions/27067251/where-to-store-jwt-in-browser-how-to-protect-against-csrf) – Mike Doe Feb 03 '20 at 07:45
-
Maybe you have a small confusion, XSS and CSRF are not the same. CSRF is preventable through JWT Tokens as Stavm suggested, XSS should be avoided through carefully managing user inputs. – mikegross Feb 03 '20 at 08:11
2 Answers
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.

- 6,864
- 6
- 55
- 61
-
https://angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances – Nebex Elias Feb 18 '20 at 11:51
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.

- 7,833
- 5
- 44
- 68
-
2What "name" so you give this cookie? How can it be used in place of "Authorization": "Bearer _______" when making http requests? – Jim Oct 11 '21 at 01:05
-
how could you use to httpOnly in angular ? i have read that we couldnot set httpOnly in angular or client side!! – Mohammed Apr 27 '22 at 12:42
-
do you have separate CSRF protection then? If JWT is not sent in a header in the client, you lose the CSRF benefit. – java-addict301 May 26 '22 at 22:31