Description
This example shows how to use Rocket request guards for authentication with JSON Web Tokens (JWT for short). The idea is that all requests authenticate first at the/login
route on a given web service 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.
However, this example only makes use of symmetric encoding and validation on the expiration claim.
You can clone the example below by running the following (you’ll need shuttle
CLI installed):
/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.
Code
Cargo.toml
main.rs
should look like this:
main.rs
claims.rs
should look like this:
claims.rs
Usage
Once you’ve cloned this example, launch it locally by usingshuttle 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:
/refresh
endpoint that takes an active token and returns a new token with a refreshed expiration time.