OAuth 2.0 and JWT Authorization in Rust: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to OAuth 2.0 and JWT in Rust



Modern web applications require reliable and secure authentication. Two key standards in this area are OAuth 2.0 (authorization protocol) and JWT (JSON Web Token, access token format). Rust, thanks to its performance and memory safety, is becoming an excellent choice for building APIs where speed and reliability are critical.



In this article, we will explore how to implement OAuth 2.0 and JWT authorization in Rust using popular crates. You will learn how to set up a server, issue and verify JWT tokens, and integrate the OAuth 2.0 flow. This material is intended for developers familiar with the basics of Rust and web frameworks.



Core Concepts of OAuth 2.0 and JWT



What is OAuth 2.0?

OAuth 2.0 is a delegated access protocol. It allows an application to obtain limited access to a user's resources without sharing their credentials (username and password). The main participants are:

  • Resource Owner — the user who owns the data.
  • Client — our application (e.g., a Rust web service).
  • Authorization Server — the server that issues tokens after successful authentication.
  • Resource Server — the API that provides protected data.


What is JWT?

JWT is a compact, URL-safe token format consisting of three parts: header, payload, and signature. The signature guarantees data integrity. JWT is often used as an access token in OAuth 2.0 because it is self-contained: the server can verify it without querying a database.



Practical Implementation in Rust

For implementation, we will need the following crates:

  • actix-web — web framework.
  • serde and serde_json — for serialization/deserialization.
  • jsonwebtoken — for working with JWT.
  • dotenv — for configuration management.
  • chrono — for working with dates and times.


Step 1: Project Setup and Structure

Create a new Cargo project and add dependencies to Cargo.toml:

[dependencies]actix-web = "4"actix-rt = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"jsonwebtoken = "9"dotenv = "0.15"chrono = { version = "0.4", features = ["serde"] }uuid = { version = "1", features = ["v4"] }


Create a .env file to store the secret key:

JWT_SECRET=my_super_secret_key_12345


Step 2: Creating Data Models and JWT Functions

Let's define structures for JWT and implement functions for creating and verifying tokens.

use chrono::{Utc, Duration};use jsonwebtoken::{encode, decode, Header, Validation, EncodingKey, DecodingKey};use serde::{Deserialize, Serialize};use std::env;

#[derive(Debug, Serialize, Deserialize)]pub struct Claims { pub sub: String, // user identifier pub exp: usize, // expiration time (timestamp) pub iat: usize, // issued at time (timestamp)}

pub fn create_jwt(user_id: &str) -> Result<String, jsonwebtoken::errors::Error> { let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set"); let now = Utc::now(); let expiration = now + Duration::hours(24); // token lives for 24 hours

let claims = Claims { sub: user_id.to_owned(), exp: expiration.timestamp() as usize, iat: now.timestamp() as usize, };

let token = encode( &Header::default(), &claims, &EncodingKey::from_secret(secret.as_bytes()), )?; Ok(token)}

pub fn validate_jwt(token: &str) -> Result<Claims, jsonwebtoken

Blogs

Book Recommendations