Cookie Authentication
Explore how you can secure your Actix Web application by using cookies.
Description
This example shows how to use authentication within actix-web with cookies, assisted by actix-identity and actix-session. The idea is that all requests authenticate first at the login route to get a cookie, then the cookie is sent with all requests requiring authentication using the HTTP cookie header.
You can clone the example below by running the following (you’ll need cargo-shuttle
installed):
Three Actix Web 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 cookie./private
: a route that will display whether you’re logged in or not, based on if you’re logged in.
The example uses actix-identity
and actix-session
with a cookie store to assist with easy setup.
Code
Your main.rs
should look like this:
Usage
Once you’ve cloned this example, launch it locally by using cargo 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:
But trying to access the private endpoint will return “Hello anonymous”:
So let’s get a cookie from the login route first:
Accessing the private endpoint with the token will now succeed:
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.
Since tokens usually have a longer than 5 minutes expiration time, we can create a /refresh
endpoint that takes an active token and returns a new token with a refreshed expiration time.
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
Was this page helpful?