Blog post

Building an authentication system in Rust using session tokens

2022-08-17T15:00:00

32 minute read

Most websites have some kind of user system. But implementing authentication can be a bit complex. It requires several things working together.

Making sure the system is secure is daunting. How do we know others cannot easily log into accounts and make edits on other people's behalf? And building stateful systems is difficult.

Today we will look at a minimal implementation in Rust. For this demo we won't be using a specific authentication library, instead writing from scratch using our own database and backend API.

We will be walking through implementing the system including a frontend for interacting with it. We will be using Axum for routing and other handling logic. The source code for this tutorial can be found here. We will then deploy the code on shuttle, which will handle running the server and giving us access to a Postgres server.

To prevent this post from being an hour long, some things are skipped over (such as error handling) and so might not match up one-to-one with the tutorial. This post also assumes basic knowledge of HTML, web servers, databases and Rust.

This isn't verified to be secure, use it at your own risk!!

Let's get started

First, we will install shuttle for creating the project (and later for deployment). If you don't already have it you can install it with cargo install cargo-shuttle. We will first go to a new directory for our project and create a new Axum app with cargo shuttle init --axum.

You should see the following in src/lib.rs:

1use axum::{routing::get, Router};

2use sync_wrapper::SyncWrapper;

3

4async fn hello_world() -> &'static str {

5    "Hello, world!"

6}

7

8#[shuttle_service::main]

9async fn axum() -> shuttle_service::ShuttleAxum {

10    let router = Router::new().route("/hello", get(hello_world));

11    let sync_wrapper = SyncWrapper::new(router);

12

13    Ok(sync_wrapper)

14}
15

Templates

For generating HTML we will be using Tera, so we can go ahead and add this with cargo add tera. We will store all our templates in a template directory in the project root.

We want a general layout for our site, so we create a base layout. In our base layout, we can add specific tags that will apply to all pages such as a Google font. With this layout all the content will be injected in place of {% block content %}{% endblock content %}:

1<!-- in "templates/base.html" -->

2<!DOCTYPE html>

3<html lang="en">

4<head>

5    <meta charset="UTF-8">

6    <meta http-equiv="X-UA-Compatible" content="IE=edge">

7    <meta name="viewport" content="width=device-width, initial-scale=1.0">

8    <title>Title</title>

9    <link rel="preconnect" href="https://fonts.googleapis.com">

10    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

11    <link href="https://fonts.googleapis.com/css2?family=Karla:wght@500&display=swap" rel="stylesheet">

12    <link href="/styles.css" rel="stylesheet">

13</head>

14<body>

15    {% block content %}{% endblock content %}

16</body>

17</html>
18

And now we can create our first page that will be displayed under the / path

1<!-- in "templates/index.html" -->

2{% extends "base.html" %}

3{% block content %}

4<h1>Hello world</h1>

5{% endblock content %}
6

Now we have our template, we need to register it under a Tera instance. Tera has a nice filesystem-based registration system, but we will use the include_str! macro so that the content is in the binary. This way we don't have to deal with the complexities of a filesystem at runtime. We register both templates so that the index page knows about base.html.

1let mut tera = Tera::default();

2tera.add_raw_templates(vec![

3    ("base.html", include_str!("../templates/base.html")),

4    ("index", include_str!("../templates/index.html")),

5])

6.unwrap();
7

We add it via an Extension (wrapped in Arc so that extension cloning does not deep clone all the templates)

1#[shuttle_service::main]

2async fn axum() -> shuttle_service::ShuttleAxum {

3    let mut tera = Tera::default();

4    tera.add_raw_templates(vec![

5        ("base.html", include_str!("../templates/base.html")),

6        ("index", include_str!("../templates/index.html")),

7    ])

8    .unwrap();

9

10    let router = Router::new()

11        .route("/hello", get(hello_world))

12        .layer(Extension(Arc::new(tera)));

13

14    let sync_wrapper = SyncWrapper::new(router);

15    Ok(sync_wrapper)

16}
17

Rendering views

Now we have created our Tera instance we want it to be accessible to our get methods. To do this in Axum, we add the extension as a parameter to our function. In Axum, an Extension is a unit struct. Rather than dealing with .0 to access fields, we use destructuring in the parameter (if you thought that syntax looks weird).

1async fn index(

2    Extension(templates): Extension<Templates>,

3) -> impl IntoResponse {

4    Html(templates.render("index", &Context::new()).unwrap())

5}
6

Serving assets

We can create a public/styles.css file

1body {

2    font-family: 'Karla', sans-serif;

3    font-size: 12pt;

4}
5

And easily create a new endpoint for it to be served from:

1async fn styles() -> impl IntoResponse {

2    Response::builder()

3        .status(http::StatusCode::OK)

4        .header("Content-Type", "text/css")

5        .body(include_str!("../public/styles.css").to_owned())

6        .unwrap()

7}
8

Here we again are using include_str! to not have to worry about the filesystem at runtime. ServeDir is an alternative if you have a filesystem at runtime. You can use this method for other static assets like JavaScript and favicons.

Running

We will add our two new routes to the router (and remove the default "hello world" one) to get:

1let router = Router::new()

2    .route("/", get(index))

3    .route("/styles.css", get(styles))

4    .layer(Extension(Arc::new(tera)));
5

With our main service we can now test it locally with cargo shuttle run.

Nice!

Adding users

We will start with a user's table in SQL. (this is defined in schema.sql).

1CREATE TABLE users (

2    id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY,

3    username text NOT NULL UNIQUE,

4    password text NOT NULL

5);
6

The id is generated by the database using a sequence. The id is a primary key, which we will use to reference users. It is better to use a fixed value field for identification rather than using something like the username field because you may add the ability to change usernames, which can leave things pointing to the wrong places.

Registering our database

Before our app can use the database we have to add sqlx with some features: cargo add sqlx -F postgres runtime-tokio-native-tls. We will also enable the Postgres feature for shuttle with cargo add shuttle-service -F sqlx-postgres.

Now back in the code we add a parameter with #[shared::Postgres] pool: Database. The #[shared::Postgres] annotation tells shuttle to provision a Postgres database using the infrastructure from code design!

1type Database = sqlx::PgPool;

2

3#[shuttle_service::main]

4async fn axum(

5    #[shared::Postgres] pool: Database

6) -> ShuttleAxum {

7    // Build tera as before

8    

9    let router = Router::new()

10        .route("/", get(index))

11        .route("/styles.css", get(styles))

12        .layer(Extension(Arc::new(tera)))

13        .layer(pool);

14    

15    // Wrap and return router as before

16}
17

Signup

For getting users into our database, we will create a post handler. In our handler, we will parse data using multipart. I wrote a simple parser for multipart that we will use here. The below example contains some error handling that we will ignore for now.

1async fn post_signup(

2    Extension(database): Extension<Database>,

3    multipart: Multipart,

4) -> impl IntoResponse {

5    let data = parse_multipart(multipart)

6        .await

7        .map_err(|err| error_page(&err))?;

8

9    if let (Some(username), Some(password), Some(confirm_password)) = (

10        data.get("username"),

11        data.get("password"),

12        data.get("confirm_password"),

13    ) {

14        if password != confirm_password {

15            return Err(error_page(&SignupError::PasswordsDoNotMatch));

16        }

17

18        let user_id = create_user(username, password, database);

19

20        Ok(todo!())

21    } else {

22        Err(error_page(&SignupError::MissingDetails))

23    }

24}
25

Creating users and storing passwords safety

When storing passwords in a database, for security reasons we don't want them to be in the exact format as plain text. To transform them away from the plain text format we will use a cryptographic hash function from pbkdf2 (cargo add pbkdf2):

1fn create_user(username: &str, password: &str, database: &Database) -> Result<i32, SignupError> {

2    let salt = SaltString::generate(&mut OsRng);

3    // Hash password to PHC string ($pbkdf2-sha256$...)

4    let hashed_password = Pbkdf2.hash_password(password.as_bytes(), &salt).unwrap().to_string();

5

6    // ...

7}
8

With hashing, if someone gets the value in the password field they cannot find out the actual password value. The only thing this value allows is whether a plain text password matches this value. And with salting different names are encoded differently. Here all these passwords were registered as "password", but they have different values in the database because of salting.

1postgres=> select * from users;

2 id | username |                                            password

3----+----------+------------------------------------------------------------------------------------------------

4  1 | user1    | $pbkdf2-sha256$i=10000,l=32$uC5/1ngPBs176UkRjDbrJg$mPZhv4FfC6HAfdCVHW/djgOT9xHVAlbuHJ8Lqu7R0eU

5  2 | user2    | $pbkdf2-sha256$i=10000,l=32$4mHGcEhTCT7SD48EouZwhg$A/L3TuK/Osq6l41EumohoZsVCknb/wiaym57Og0Oigs

6  3 | user3    | $pbkdf2-sha256$i=10000,l=32$lHJfNN7oJTabvSHfukjVgA$2rlvCjQKjs94ZvANlo9se+1ChzFVu+B22im6f2J0W9w

7(3 rows)
8

With the following simple database query and our hashed password, we can insert users.

1fn create_user(username: &str, password: &str, database: &Database) -> Result<i32, SignupError> {

2    // ...

3

4    const INSERT_QUERY: &str =

5        "INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id;";

6

7    let fetch_one = sqlx::query_as(INSERT_QUERY)

8        .bind(username)

9        .bind(hashed_password)

10        .fetch_one(database)

11        .await;

12    

13    // ...

14}
15

And we can handle the response and get the new user id with the following:

1fn create_user(username: &str, password: &str, database: &Database) -> Result<i32, SignupError> {

2    // ...

3

4    match fetch_one {

5        Ok((user_id,)) => Ok(user_id),

6        Err(sqlx::Error::Database(database))

7            if database.constraint() == Some("users_username_key") =>

8        {

9            return Err(SignupError::UsernameExists);

10        }

11        Err(err) => {

12            return Err(SignupError::InternalError);

13        }

14    }

15}
16

Great now we have the signup handler written, let's create a way to invoke it in the UI.

Using HTML forms

To invoke the endpoint with multipart we will use an HTML form.

1<!-- in "templates/signup.html" -->

2{% extends "base.html" %}

3{% block content %}

4<form action="/signup" enctype="multipart/form-data" method="post">

5    <label for="username">Username</label>

6    <input type="text" name="username" id="username" minlength="1" maxlength="20" pattern="[0-9a-z]+" required>

7    <label for="password">Password</label>

8    <input type="password" name="password" id="password" required>

9    <label for="confirm_password">Confirm Password</label>

10    <input type="password" name="confirm_password" id="confirm_password" required>

11    <input type="submit" value="Signup">

12</form>

13{% endblock content %}
14

Notice the action and method that correspond to the route we just added. Notice also the enctype being multipart, which matches what we are parsing in the handler. The above has a few attributes to do some client-side validation, but in the full demo it is also handled on the server.

We create a handler for this markup in the same way as done for our index with:

1async fn get_signup(

2    Extension(templates): Extension<Templates>,

3) -> impl IntoResponse {

4    Html(templates.render("signup", &Context::new()).unwrap())

5}
6

We can add signup to the Tera instance and then add both the get and post handlers to the router by adding it to the chain:

1.route("/signup", get(get_signup).post(post_signup))
2

Sessions

Once signed up, we want to save the logged-in state. We don't want the user to have to send their username and password for every request they make.

Cookies and session tokens

Cookies help store the state between browser requests. When a response is sent down with Set-Cookie, then any subsequent requests the browser/client makes will send cookie information. We can then pull this information off of headers on requests on the server.

Again, these need to be safe. We don't want collisions/duplicates. We want it to be hard to guess. For these reasons, we will represent it as a 128-bit unsigned integer. This has 2^128 options, so a very low chance of a collision.

We want to generate a "session token". We want the tokens to be cryptographically secure. Given a session id, we don't want users to be able to find the next one. A simple globally incremented u128 wouldn't be secure because if I know I have session 10 then I can send requests with session 11 for the user who logged in after. With a cryptographically secure generator, there isn't a distinguishing pattern between subsequently generated tokens. We will use the ChaCha algorithm/crate (we will add cargo add rand_core rand_chacha). We can see that it does implement the crypto marker-trait confirming it is valid for cryptographic scenarios.

This is unlike Pseudo-random number generators where you can predict the next random number given a start point and the algorithm. This could be a problem if we have our token we can get the session token of the person who logged in after us really easy and thus impersonate them.

To initialize the random generator we use SeedableRng::from_seed. The seed in this case is an initial state for the generator. Here we use OsRng.next_u64() which retrieves randomness from the operating system rather a seed. We will be doing something similar to the creation of the Tera instance. We must wrap it in an arc and a mutex because generating new identifiers requires mutable access. We now have the following main function:

1#[shuttle_service::main]

2async fn axum(

3    #[shared::Postgres] pool: Database

4) -> ShuttleAxum {

5    // Build tera as before

6

7    let random = ChaCha8Rng::seed_from_u64(OsRng.next_u64())

8    

9    let router = Router::new()

10        .route("/", get(index))

11        .route("/styles.css", get(styles))

12        .route("/signup", get(get_signup).post(post_signup))

13        .layer(Extension(Arc::new(tera)))

14        .layer(pool)

15        .layer(Extension(Arc::new(Mutex::new(random))));

16    

17    // Wrap and return router as before

18}
19

Adding sessions to signup

As well as creating a user on signup, we will create the session token for the newly signed-up user. We post it to the table with our user_id

1type Random = Arc<Mutex<ChaCha8Rng>>;

2

3pub(crate) async fn new_session(

4    database: &Database, 

5    random: Random, 

6    user_id: i32

7) -> String {

8    const QUERY: &str = "INSERT INTO sessions (session_token, user_id) VALUES ($1, $2);";

9

10    let mut u128_pool = [0u8; 16];

11    random.lock().unwrap().fill_bytes(&mut u128_pool);

12

13    // endian doesn't matter here

14    let session_token = u128::from_le_bytes(u128_pool);

15

16    let _result = sqlx::query(QUERY)

17        .bind(&session_token.to_le_bytes().to_vec())

18        .bind(user_id)

19        .execute(database)

20        .await

21        .unwrap();

22

23    session_token

24}
25

In the full demo, we use the new type pattern over a u128 to make this easier, but we will stick with a u128 type here.

Now we have our token, we need to package it into a cookie value. We will do it in the simplest way possible, using .to_string(). We will send a response that does two things, sets this new value and returns/redirects us back to the index page. We will create a utility function for doing this:

1fn set_cookie(session_token: &str) -> impl IntoResponse {

2    http::Response::builder()

3        .status(http::StatusCode::SEE_OTHER)

4        .header("Location", "/")

5        .header("Set-Cookie", format!("session_token={}; Max-Age=999999", session_token))

6        .body(http_body::Empty::new())

7        .unwrap()

8}
9

Now we can complete our signup handler by adding random as a parameter and returning our set cookie response.

1async fn post_signup(

2    Extension(database): Extension<Database>,

3    Extension(random): Extension<Random>,

4    multipart: Multipart,

5) -> impl IntoResponse {

6    let data = parse_multipart(multipart)

7        .await

8        .map_err(|err| error_page(&err))?;

9

10    if let (Some(username), Some(password), Some(confirm_password)) = (

11        data.get("username"),

12        data.get("password"),

13        data.get("confirm_password"),

14    ) {

15        if password != confirm_password {

16            return Err(error_page(&SignupError::PasswordsDoNotMatch));

17        }

18

19        let user_id = create_user(username, password, &database);

20

21        let session_token = new_session(database, random, user_id);

22

23        Ok(set_cookie(&session_token))

24    } else {

25        Err(error_page(&SignupError::MissingDetails))

26    }

27}

28let session_token = new_session(database, random, user_id);
29

Using the session token

Great so now we have a token/identifier for a session. Now we can use this as a key to get information about users.

We can pull the cookie value using the following spaghetti of iterators and options:

1let session_token = req

2    .headers()

3    .get_all("Cookie")

4    .iter()

5    .filter_map(|cookie| {

6        cookie

7            .to_str()

8            .ok()

9            .and_then(|cookie| cookie.parse::<cookie::Cookie>().ok())

10    })

11    .find_map(|cookie| {

12        (cookie.name() == USER_COOKIE_NAME).then(move || cookie.value().to_owned())

13    })

14    .and_then(|cookie_value| cookie_value.parse::<u128>().ok());
15

Auth middleware

In the last post, we went into detail about middleware. You can read more about it in more detail there.

In our middleware, we will get a little fancy and make the user pulling lazy. This is so that requests that don't need user data don't have to make a database trip. Rather than adding our user straight onto the request, we split things apart. We first create an AuthState which contains the session token, the database, and a placeholder for our user (Option<User>)

1#[derive(Clone)]

2pub(crate) struct AuthState(Option<(u128, Option<User>, Database)>);

3

4pub(crate) async fn auth<B>(

5    mut req: http::Request<B>,

6    next: axum::middleware::Next<B>,

7    database: Database,

8) -> axum::response::Response {

9    let session_token = /* cookie logic from above */;

10

11    req.extensions_mut()

12        .insert(AuthState(session_token.map(|v| (v, None, database))));

13

14    next.run(req).await

15}
16

Then we create a method on AuthState which makes the database request.

Now we have the user's token we need to get their information. We can do that using SQL joins

1impl AuthState {

2    pub async fn get_user(&mut self) -> Option<&User> {

3        let (session_token, store, database) = self.0.as_mut()?;

4        if store.is_none() {

5            const QUERY: &str =

6                "SELECT id, username FROM users JOIN sessions ON user_id = id WHERE session_token = $1;";

7

8            let user: Option<(i32, String)> = sqlx::query_as(QUERY)

9                .bind(&session_token.to_le_bytes().to_vec())

10                .fetch_optional(&*database)

11                .await

12                .unwrap();

13

14            if let Some((_id, username)) = user {

15                *store = Some(User { username });

16            }

17        }

18        store.as_ref()

19    }

20}
21

Here we cache the user internally using an Option. With the caching in place if another middleware gets the user and then a different handler tries to get the user it results in one database request, not two!

We can add the middleware to our chain using:

1#[shuttle_service::main]

2async fn axum(

3    #[shared::Postgres] pool: Database

4) -> ShuttleAxum {

5    // tera and random creation as before

6

7    let middleware_database = database.clone();

8    

9    let router = Router::new()

10        .route("/", get(index))

11        .route("/styles.css", get(styles))

12        .route("/signup", get(get_signup).post(post_signup))

13        .layer(axum::middleware::from_fn(move |req, next| {

14            auth(req, next, middleware_database.clone())

15        }))

16        .layer(Extension(Arc::new(tera)))

17        .layer(pool)

18        .layer(Extension(Arc::new(Mutex::new(random))));

19    

20    // Wrap and return router as before

21}
22

Getting middleware and displaying our user info

Modifying our index Tera template, we can add an "if block" to show a status if the user is logged in.

1<!-- in "templates/index.html" -->

2{% extends "base.html" %}

3{% block content %}

4<h1>Hello world</h1>

5{% if username %}

6    <h3>Logged in: {{ username }}</h3>

7{% endif %}

8{% endblock content %}
9

Using our middleware in requests is easy in Axum by including a reference to it in the parameters. We then add the username to the context for it to be rendered on the page.

1async fn index(

2    Extension(current_user): Extension<AuthState>,

3    Extension(templates): Extension<Templates>,

4) -> impl IntoResponse {

5    let mut context = Context::new();

6    if let Some(user) = current_user.get_user().await {

7        context.insert("username", &user.username);

8    }

9    Html(templates.render("index", &context).unwrap())

10}
11

Logging in and logging out

Great we can signup and that now puts us in a session. We may want to log out and drop the session. This is very simple to do by returning a response with the cookie Max-Age set to 0.

1pub(crate) async fn logout_response() -> impl axum::response::IntoResponse {

2    Response::builder()

3        .status(http::StatusCode::SEE_OTHER)

4        .header("Location", "/")

5        .header("Set-Cookie", "session_token=_; Max-Age=0")

6        .body(Empty::new())

7        .unwrap()

8}
9

For logging in we have a very similar logic for signup with pulling multipart information of a post request. Unlike signup, we don't want to create a new user. We want to check the row with that username has a password that matches. If the credentials match then we create a new session:

1async fn post_login(

2    Extension(database): Extension<Database>,

3    multipart: Multipart,

4) -> impl IntoResponse {

5    let data = parse_multipart(multipart)

6        .await

7        .map_err(|err| error_page(&err))?;

8

9    if let (Some(username), Some(password)) = (data.get("username"), data.get("password")) {

10        const LOGIN_QUERY: &str = "SELECT id, password FROM users WHERE users.username = $1;";

11

12        let row: Option<(i32, String)> = sqlx::query_as(LOGIN_QUERY)

13            .bind(username)

14            .fetch_optional(database)

15            .await

16            .unwrap();

17

18        let (user_id, hashed_password) = if let Some(row) = row {

19            row

20        } else {

21            return Err(LoginError::UserDoesNotExist);

22        };

23

24        // Verify password against PHC string

25        let parsed_hash = PasswordHash::new(&hashed_password).unwrap();

26        if let Err(_err) = Pbkdf2.verify_password(password.as_bytes(), &parsed_hash) {

27            return Err(LoginError::WrongPassword);

28        }

29

30        let session_token = new_session(database, random, user_id);

31

32

33        Ok(set_cookie(&session_token))

34    } else {

35        Err(error_page(&LoginError::NoData))

36    }

37}
38

Then we refer back to the signup section and replicate the same HTML form and handler that renders the Tera template as seen before but for a login screen. At the end of that we can add two new routes with three handlers completing the demo:

1#[shuttle_service::main]

2async fn axum(

3    #[shared::Postgres] pool: Database

4) -> ShuttleAxum {

5    // tera, middleware and random creation as before

6    

7    let router = Router::new()

8        // ...

9        .route("/logout", post(logout_response))

10        .route("/login", get(get_login).post(post_login))

11        // ...

12

13    // Wrap and return router as before

14}
15

Deployment

This is great, we now have a site with signup and login functionality. But we have no users, our friends can't log in on our localhost. We want it live on the interwebs. Luckily we are using shuttle, so it is as simple as:

cargo shuttle deploy

Because of our #[shuttle_service::main] annotation and out-the-box Axum support our deployment doesn't need any prior config, it is instantly live!

Now you can go ahead with these concepts and add functionality for listing and deleting users. The full demo implements these if you are looking for clues.

Thoughts building the tutorial and other ideas on where to take it

This demo includes the minimum required for authentication. Hopefully, the concepts and snippets are useful for building it into an existing site or for starting a site that needs authentication. If you were to continue, it would be as simple as more fields onto the user object or building relations with the id field on the user's table. I will leave it out with some of my thoughts and opinions while building the site as well as things you could try extending it with.

For templating Tera is great. I like how I separate the markup into external files rather than bundling it into src/lib.rs. Its API is easy to use and is well documented. However, it is quite a simple system. I had a few errors where I would rename or remove templates and because the template picker for rendering uses a map it can panic at runtime if the template does not exist. It would be nice if the system allowed checking that templates exist at compile time. The data sending works on serde serialization, which is a little bit more computation overhead than I would like. It also does not support streaming. With streaming, we could send a chunk of HTML that doesn't depend on database values first, and then we can add more content when the database transaction has gone through. If it supported streaming we could avoid the all-or-nothing pages with white page pauses and start connections to services like Google Fonts earlier. Let me know what your favorite templating engine is for Rust and whether it supports those features!

For working with the database, sqlx has typed macros. I didn't use them here but for more complex queries you might prefer the type-checking behavior. Maybe 16 bytes for storing session tokens is a bit overkill. You also might want to try sharding that table if you have a lot of sessions or using a key-value store (such as Redis) might be simpler. We also didn't implement cleaning up the sessions table, if you were storing sessions using Redis you could use the EXPIRE command to automatically remove old keys.

This blog post is powered by shuttle! The serverless platform built for Rust.

Shuttle: Stateful Serverless for Rust

Deploying and managing your Rust web apps can be an expensive, anxious and time consuming process.

If you want a batteries included and ops-free experience, try out shuttle.


Share this article

Let's make Rust the next language of cloud-native

We love you Go, but Rust is just better.