Question

What is the proper way of combining session-based authentication with stateless, token-based authentication for a REST API?

Use case:

  1. User logs-in in the standard, traditional, session-based way. Most of the website uses this login flow.
  2. On one of the pages, a JavaScript script wants to request some data from a RESTful stateless API on behalf of the user

I expect the JavaScript script will need to be given something in the page (e.g. in meta tags) as the page loads to be able to authenticate with the API. The API uses OAuth2.

What should it be and how best to give it to JavaScript?

  • The code in the Authorization Code grant? This would mean JavaScript will have to make another authorization request to get the access token.
  • The access token itself? This feels insecure, outputting the access token into the HTML of the page.
  • Something else?

How to give it to JavaScript?

  • Meta tag?
  • Headers?
  • Something else?

The OAuth documentation / tutorials are really unclear about this.

Was it helpful?

Solution

So "standard, traditional, session-based" auth is a cookie on the client with a guid and an in memory database on the server which hold the data for that user

"stateless, token-based authentication" just takes the data on the server, puts it in the cookie and signs it.

All you need to do is have the server create a token and send it to the client instead of the sessionid cookie. You can put the info in a cookie.

OTHER TIPS

This article walks through various ways to use OAuth2. It might help you work through this.

Based on the article and the relevant RFC, you would not pass the access token to the user agent (e.g. browser). The authorization grant is passed to the client (web server) and it then uses the authorization code to retrieve the access token directly.

The other option that seems relevant here is the implicit grant style. In this case the access token is indeed provided back to the user agent in a redirect URI. You can potentially improve on this slightly by passing the token in a header instead of the URI as noted in the article. The use of headers here aligns with OWASP recommendations.

So more or less, it seems you are on the right track, you just need to choose between the extra overhead of having the client web server call for the access token or the potential risk of passing the access token back to the user's browser. The length of time the access tokens and authorization grants are valid is important to consider when weighing the options.

Be sure to check the end of the article as it discusses some ways to avoid pitfalls in either approach.

Licensed under: CC-BY-SA with attribution
scroll top