grahamhoyes
grahamhoyes

Reputation: 321

Refreshing OAuth2 Access Tokens in Serverless Application

I'm creating a project in Django (v2.2) with a REST backend though Django Rest Framework (v3.9.4). This REST API is consumed by both SPAs and headless applications running on external servers. All views require user authentication with appropriate permissions.

The front-end SPAs are able to use Session Authentication and pass this along to the REST API no problem. However, Session Authentication is not appropriate for headless servers and autonomous functions that we want to be able to consume the API as well.

I've settled on using Django OAuth Toolkit (v1.2.0) to provide authentication using OAuth2.

My issue is as follows. Developers who wish to consume the API from some headless environment can generate an access token using password-based or client credentials grant type (or any of the other types, really). This gives them an access token, an expiry time, and a refresh token.

For applications which have a stateful server, they can store the access and refresh tokens in a file, environment variable, etc. When the token expires, they can use the refresh token to acquire a new access token, and overwrite the file or environment variable so that it is available going forward.

However, some of our applications exist as Google Cloud Functions or Docker containers deployed by Jenkins. With a non-expiring access token, we could pass the token into these like any other secret credential and the application would be good to go. The crux of my problem is what should these serverless applications do when the access token expires? They will need to use the refresh token, but the new access token will need to be available in future invocations of the Cloud Function (which requires re-deploying to set environment variables) or Docker container (through Jenkins' credential manager to again set environment variables in the container).

By default, tokens expire every hour, and expiry cannot be disabled. I would like to avoid the workaround of setting an expiry time to some large amount.

Any suggestions on either direct solutions, or other best practices for managing expiring access tokens in trusted clients would be much appreciated!


Edit for clarification In a Google Cloud function, we can set an access token to be available as an environment variable to all invocations of that function (specifically an encrypted environemnt variable, decrypted using Google KMS). That environment variable is read in the cloud function, and passed to API requests with the Authorization: Bearer <token> header. When that access token expires, we would need to update the environment variable for future invocations, which would involve re-deploying the cloud function through the gcloud functions command line tool.

Upvotes: 0

Views: 646

Answers (0)

Related Questions