3
votes

I added jwt based auth to my api, works with adding the token to the header (Authorization : Bearer {tokenhere}).

I had a look into how to store it on the client side, and the most recommended method was to use HttpOnly cookie, which is set on the server, so client code cannot access it. The browser will get it and attach it to future requests.

For this to work, the server has to write this cookie in a response, and be able to validate it instead of the token in the header (Authorization : Bearer {tokenhere}).

How do I set this up? I searched how and low, and didn't find a tutorial on this, it's either cookie or jwt, never jwt stored as an httponly cookie.

2

2 Answers

3
votes

I found 2 answers, either:

-catch the request and move the token from the cookie to the header as auth bearer, so when it gets to handling the jwt auth it will get it like that (How to properly refresh a token using JWT + HttpOnly Cookie?)

-override the jwt handler event and overwrite the token reading it from the cookie (In ASP.NET Core read JWT token from Cookie instead of Headers)

writing it to a cookie is no big deal, in the login method I just do this:

HttpContext.Response.Cookies.Append("access_token", tokens.AccessToken, new CookieOptions { HttpOnly = true });
-2
votes

It’s a web api you say, so you don’t need to store it. You basically need to check that there is a valid bearer token on every request that comes to your web api. The scenario of saving the token/cookie happens when there is a user agent in question, in that case you start a user session and the session id is saved in the cookie, which get passed to your server on every subsequent request and that’s how you know it’s the same user.

Even in the later case people choose not to save those tokens in the cookie so as to prevent the cookie size becoming huge. And the point is that you don’t need to, you authenticate the user and you save his role, identity etc in your website’s session so there is no need for the token anymore. For web apis however, there is no state and you should be validating every request for the presence of a bearer token.