I have a Laravel project that uses Laravel Sanctum to generate access tokens for users.
I return the token to the front-end on a login and sign up request.
Previously, I’d use Laravel’s session()
function to store tokens like so:
session(['token', $accessToken]);
But I’ve been told this is not secure. So now I return it to the front-end (vanilla Javascript) and store it in a cookie. But I’m also being told that’s not secure.
Can someone please guide me on where and how exactly I should store the token?
I’ve heard about setting a httpOnly
flag, but nowhere actually telling me where to store the token.
5
Answers
Use Local storage to store your access tokens
Skype also use local storage to store access token
FYK
My personal opinion is, If you’re using cookies to use with
httponly
andsecure
httpOnly
It means the cookie can’t be accessed by JavaScript
secure
To protect against MITM, set the secure flag for the cookie
you don’t need to store token if you are using laravel Sanctum package, when you install and migrate it will create personal_access_tokens table where all users token has been stored. Typical usage is like when use login you can generate to
and on signout you can destroy the token like that
you not need to store token in session or cookie as it’s risky
You should store them in the session like you said in your post.
As long as you are using TLS (HTTPS) this will be safe in the majority of situations.
This is a whole different issue that is not really related to the session itself. People can try to guess the session ID etc. Laravel uses random, long session ID’s that are stored in an encrypted cookie. Unless your application has a major security flaw, you shouldn’t have to worry about it.
Sure, you could copy a session cookie to a different browser, but this is just how sessions work.
If you want to be really sure that the session was not hijacked:
You should not be storing the token at all, especially the plain text token, if you are using Sanctum. After you login-in your user you create a token for them and send back the plan text token to the user. Than the user uses that token for every subsequent request.
If you need to retrieve the token on your backend you can do
auth()->user()->currentAccessToken()