Chapter 32: JWT Authentication in Rust

Sign and verify tokens with HS256, RS256. In this chapter, you will learn jwt authentication in depth with Rust code examples, explanations, and best practices.

Overview

This chapter covers jwt authentication for Kungfu.js developers using Rust. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding jwt authentication is essential because it is a core part of building web applications. Every real-world app needs to handle sign and verify tokens with hs256, rs256. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how authentication works in Rust:

use kungfu_core::auth::{JwtService, JwtConfig, auth_jwt};

let jwt = JwtService::new("your-secret-key");

// Sign a token
let token = jwt.sign(&json!({
    "sub": "user123",
    "role": "admin",
    "exp": 9999999999,
}))?;

// Verify a token
let claims: serde_json::Value = jwt.verify(&token)?;

// Protect routes with middleware
Kungfu::new()
    .use_middleware(auth_jwt(JwtConfig::new("your-secret-key")))
    .handle_get("/protected", |_req, res| res.text("secret"))

Security Best Practices

Never store passwords in plain text. Kungfu.js uses Argon2id, which is the winner of the Password Hashing Competition. It is designed to be resistant to GPU and ASIC attacks.

JWT tokens should have an expiration time. A good default is 1 hour for access tokens and 7 days for refresh tokens. Kungfu.js validates the expiration automatically.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about jwt authentication in Rust. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 33, we will cover Session Authentication: Cookie-based sessions with server store.