Browser-native way to send Bearer token

Viewed 3671

I’m currently reading through RFC 6749 (“The OAuth 2.0 Authorization Framework”) and RFC 6750 (“The OAuth 2.0 Authorization Framework: Bearer Token Usage”).

I wonder if there is a way to send the Authorization: Bearer ... header from a browser-based client, that automatically links the token to requests, like there is with Authorization: Basic ..., which can be triggered by sending a WWW-Authenticate: Basic realm="..." in a response. The browser then asks for a username and password and sets the Authorization header automatically in the next request.

Is there a way to do something similar for bearer tokens? Especially to link the token to a host or similar context that works across page refreshes?

The reason I’m asking is to avoid an unnecessary delay in having to load and parse some JavaScript that extracts the bearer token from – say – LocalStorage and setting the Authorization header. This would also allow me to have protected assets which are not requested via Ajax or Fetch requests, e.g. images (img tags).

I know a common workaround is to substitute the bearer token for a session cookie. But I’d like to know if there are other solutions to this problem.

1 Answers

ACCESS TOKEN USAGE

There are no options that will send access tokens automatically during HTML requests. They are designed to only be sent when your code explicitly requests it. This prevents certain vulnerabilities that were common with cookies.

HYBRID APPROACH

I've come to think that the best all round option for modern SPAs is to adopt the following approach:

  • Use access tokens in the browser - to support fast cross domain API calls
  • Use HTTP only cookies to handle aspects related to page reloads and multi tab browsing - where the cookie can also store or link to a refresh token

SECURING HTML ASSETS

It feels like a cookie is also the only option that will work well for your scenario. As you say, a cookie will be sent on image requests before your Javascript bundles are fully downloaded.

MY SCENARIO

I had different reasons for wanting the benefits of both cookies and tokens, to work around some token renewal problems during multi tab browsing. I wanted the overall behaviour to be that of an SPA though.

LIMITED USAGE COOKIES

In my case I used a cookie, but in a very targeted way. Perhaps in your case you could do something similar, while continuing to use access tokens for API calls.

Related