Protect backend endpoints using auth in SPA

Problem statement

I created a SPA application in Auth0 and was able to create a login flow in the front end (redirect to auth0, login/register, and redirect back to my website). How can I protect some backend endpoints and force the client to pass the token in the Authorization Bearer header?

Solution

The first step is registering your API in Auth0. This will allow you to specify an audience in your /authorize requests and have an access token issued by Auth0 for your Python backend.

e.g. if you registered an API with the identifier (audience) “https://example.com/api”, you could then add this in your /authorize parameters

Once you have an API registered and you are requesting tokens for it, you can configure your backend to trust Auth0-issued tokens by configuring its JWT validation:

You can use one of the libraries listed here to perform the validation for you, providing the issuer and audience values in its configuration for your tenant and registered API identifier respectively:

You will also need to provide the signing keys to the JWT library you choose. Below doc explains how to locate your tenant’s JWKS: