How akhilsharma90/rust-warp-jwt works
Project type and purpose
• This is a small backend example written in Rust that demonstrates JSON Web Token (JWT)–based authentication and authorization using the Warp web framework.
• There is no separate frontend or external database—everything runs in a single Rust binary. The code shows how to handle login, generate/validate tokens, and gate access to “user” vs. “admin” endpoints.
File‐structure analysis
• Cargo.toml: Rust project manifest (dependencies include warp, jsonwebtoken, serde, etc.)
• src/main.rs: entry point; initializes the HTTP server, sets up routes, and wires in the auth logic.
• src/auth.rs: core logic for signing and verifying JWTs, defining claims, roles, and token expiration.
• src/error.rs: custom error types and mappings to HTTP status codes.
Key architectural insights from README
• Three HTTP endpoints:
• POST /login → accepts credentials, issues JWT with “sub” (user ID), “role,” and “exp.”
• GET /user → requires any valid token.
• GET /admin → requires valid token with role=Admin.
• No external storage; user lookup/role check are hard‐coded in auth.rs for demonstration.
Main components
a. Clients (e.g., curl or any HTTP client)
b. HTTP Server (Warp framework)
c. Auth Module
– Credential validation (in‐memory/hard‐coded)
– JWT generation (signing with HS512)
– JWT validation (signature + claims + role checks)
d. Endpoints / Routes
– /login → issues token
– /user → middleware verifies token, returns “Hello User”
– /admin → middleware verifies token + role, returns “Hello Admin” or 401
e. Error Handler (maps internal errors to HTTP responses)
Relationships and data flow
1. Client → POST /login with email/pw → Warp routing → Auth module credentials check
2. Auth module → if OK, generate JWT → return { "token": "..." }
3. Client → GET /user or /admin with Authorization: Bearer <token>
4. Warp auth‐middleware → Auth module validates signature & expiration
5. Auth module checks role claim for /admin
6. On success → handler returns greeting; on failure → error module returns 401/403
Architectural patterns & principles
• Single‐process web service (monolith)
• Middleware for cross‐cutting concerns (authentication, error handling)
• Separation of concerns: routing in main.rs, auth logic in auth.rs, error mapping in error.rs
• Use of JWT for stateless auth—no session store
• Clear component names (e.g., “Warp HTTP Server,” “JWT Generator/Verifier”)
• Notes on token structure (claims: sub, role, exp) near the Auth Module
• Error paths leading to the Error Handler with HTTP status codes (401, 403)