11

This is my setup:

  • 1 authentication server which gives out JWT token on successfull authentication.
  • Multiple API resource servers which gives information (when the user is authenticated).

Now I want to build my ASP.NET MVC frontend. Is it ok to take the token, which I receive after authentication, and put it in a cookie so I can access it with every secured call I need to make? I use the RestSharp DLL for doing my http calls. If it has a security flaw, then where should I store my token?

I would use this code for the cookie:

            System.Web.HttpContext.Current.Response.Cookies.Add(new System.Web.HttpCookie("Token")
        {
            Value = token.access_token,
            HttpOnly = true
        });
Kaizer
  • 651
  • 3
  • 9
  • 22
  • make sure it's also HTTPS only by adding the Secure flag! – Tilo Sep 28 '16 at 20:22
  • [Answer](http://stackoverflow.com/a/40376819/204699) to related question on where to store token in browser apps may contain useful additional information. – João Angelo Nov 02 '16 at 16:11

2 Answers2

18

You’re on the right path! The cookie should always have the HttpOnly flag, setting this flag will prevent the JavaScript environment (in the web browser) from accessing the cookie. This is the best way to prevent XSS attacks in the browser.

You should also use the Secure flag in production, to ensure that the cookie is only sent over HTTPS.

You also need to prevent CSRF attacks. This is typically done by setting a value in another cookie, which must be supplied on every request.

I work at Stormpath and we’ve written a lot of information about front-end security. These two posts may be useful for understanding all the facets:

Token Based Authentication for Single Page Apps (SPAs)

https://stormpath.com/blog/build-secure-user-interfaces-using-jwts/

Drunix
  • 3,313
  • 8
  • 28
  • 50
robertjd
  • 4,723
  • 1
  • 25
  • 29
1

Are you generating your own JWTs?

If yes, you should consider using a signing algorithm based on asymetric encryption, like "RS256" or "RS512" -- this way you can verify the claims in your client application without sharing the private secret.

Do you really need to pass the JWT into the Cookie?

It might be safer to just put a random id in your Cookie, which references the JWT access token, and do the de-referencing magic on the server which serves your web-app.

Tilo
  • 33,354
  • 5
  • 79
  • 106
  • could you provide some code , how do you store jwt in cookie please?suppose `string token=YOUR_TOKEN` , and you are coding in startup class – sepehr Feb 01 '17 at 14:20