Description

This example shows how to use Axum authentication with JSON Web Tokens (JWT for short). The idea is that all requests authenticate first at a login route to get a JWT. Then the JWT is sent with all requests requiring authentication using the HTTP header Authorization: Bearer <token>.

This example uses the jsonwebtoken which supports symmetric and asymmetric secret encoding, built-in validations, and most JWT algorithms.

Three Axum routes are registered in this file:

  • /public: a route that can be called without needing any authentication.
  • /login: a route for posting a JSON object with a username and password to get a JWT.
  • /private: a route that can only be accessed with a valid JWT.

You can clone the example below by running the following (you’ll need shuttle CLI installed):

shuttle init --from shuttle-hq/shuttle-examples --subfolder axum/jwt-authentication

Code

Usage

Once you’ve cloned this example, launch it locally by using shuttle run. Once you’ve verified that it’s up, you’ll now be able to go to http://localhost:8000 and start trying the example out!

First, we should be able to access the public endpoint without any authentication using:

curl http://localhost:8000/public

But trying to access the private endpoint will fail with a 403 forbidden:

curl http://localhost:8000/private

So let’s get a JWT from the login route first:

curl -X POST --header "Content-Type: application/json" --data '{"client_id": "foo", "client_secret": "bar"}' http://localhost:8000/login

Accessing the private endpoint with the token will now succeed:

curl --header "Authorization: Bearer <token>" http://localhost:8000/private

The token is set to expire in 5 minutes, so wait a while and try to access the private endpoint again. Once the token has expired, a user will need to get a new token from login.

Looking to extend this example? Here’s a couple of ideas to get you started:

  • Create a frontend to host the login
  • Add a route for registering
  • Use a database to check login credentials

If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them right here.

Be sure to check out the examples repo for many more examples!