Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving credentials / token in a cookie?

I have managed to get working the authentication which i know return a token (JWT) to the client. This token has an expiration date/time so I was thinking about saving the token in a cookie so future logins were authenticated but this is probably not going to work.

I then though about saving the username and password in a cookie although i know this isn't recommended??

Currently i have a form that accepts a username and password, a successful login will provide a token which is used to access other endpoints.

The form needs to include a "Remember Me" so an automatic login can occur.

What is the best way of achieving this ?

Should i be storing the username and password in the cookie, if not how do i automatically authenticate the next time the user arrives to my site. The token that i provide is going to be expired so is there any point in even storing this ?

thanks in advance

like image 203
Martin Avatar asked Mar 23 '23 04:03

Martin


1 Answers

Do not store the user name or password in the cookie. Even if the cookie is encrypted, it is better to store a credential with short expiration time like the token in a cookie than a credential like password which has more shelf life.

Even in the ASP.NET Web Forms or MVC world (Forms Authentication), typically "Remember me" works only until the time the cookie expires. "Remember me" does not mean remember me for ever and there must be a finite time period for remembering. That time can be derived from a cookie. You can put the JWT in the cookie and set the cookie's life time same as JWT, say an hour. When the user comes back to your app within that time, the cookie will not expire and the user is automatically logged in. Otherwise, they have to re-login. Do not think about storing the user name - password and systematically logging in. Let the user enter the credentials and that approach will be more secure. BTW, make sure cookie is encrypted and is an HTTP only cookie.

This mechanism will be similar to Forms Authentication. In place of the authentication ticket, you will use your JWT. Instead of FAM reading the cookie, you will need to have your own HttpModule or a message handler to do that and establish the identity for the requests.

like image 167
Badri Avatar answered Apr 06 '23 00:04

Badri