Search code examples
javascripthtmloauth-2.0jwttoken

Make the browser open links with authorization header


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?


Solution

  • 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.