1

I can use JavaScript to construct custom requests using my token, jQuery example

$.ajax({
  url: "/page",
  type: 'GET',
  headers: {"Authorization": 'Bearer ' + localStorage.getItem('token')}
});

To get the page at /page which may require authentication to do.

But what if I have in my page a link

<a href="/page"></a>

The user is already authenticated, there is a token in localStorage.

How can I set it up so that clicking on the link loads a new webpage as usual, but tell the server Authorization: Bearer ... in the header of that request so the server knows the request is authentic?

1
  • 1
    It is very inadvisable to store bearer tokens in localStorage unless the payload is encrypted. Any authentication your application requires can be bypassed by a user with local privileges to the machine on which the data is stored. It's also susceptible to theft by cross-site scripting. Use sessionStorage instead. It's only available to that window/tab, and it is destroyed when the window/tab is closed. Commented Dec 13, 2023 at 8:20

1 Answer 1

4

You can't specify headers in browser navigation. If you need to authenticate when the user visits the page, you should create a cookie.

Cookies get sent in all requests. Storing your authentication token there would do what you need.

Sign up to request clarification or add additional context in comments.

5 Comments

I've read cookies are vulnerable to XSS and CSRF. Why do all the JWT tutorials say not to use a Cookie?
Because JWT's are intended to use for an API. Frontend fetches data from the API using its JWT. You can still use cookies and prevent them from being insecure. If you need authentication on navigation, JWT is the wrong tool for the job.
Cookies, like I said. Cookies are still very secure, simply it is easy to be careless with them; resulting in those vulnerabilities you mentioned.
@minseong Simply you can fix those vulnerabilities by following best practices like Domain Control, Mark as Secured and more...
JWT also has vulnerabilities. auth0.com/blog/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.