main.rs
This file
Path
examples/jwt/src/main.rs
198 lines · 5.6 KiB · Rust
Last changed by
Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7
History of this fileTake it
1//! Example JWT authorization/authentication.2//!3//! Run with4//!5//! ```not_rust6//! JWT_SECRET=secret cargo run -p example-jwt7//! ```89use axum::{10 extract::FromRequestParts,11 http::{request::Parts, StatusCode},12 response::{IntoResponse, Response},13 routing::{get, post},14 Json, RequestPartsExt, Router,15};16use axum_extra::{17 headers::{authorization::Bearer, Authorization},18 TypedHeader,19};20use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};21use serde::{Deserialize, Serialize};22use serde_json::json;23use std::fmt::Display;24use std::sync::LazyLock;25use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2627// Quick instructions28//29// - get an authorization token:30//31// curl -s \32// -w '\n' \33// -H 'Content-Type: application/json' \34// -d '{"client_id":"foo","client_secret":"bar"}' \35// http://localhost:3000/authorize36//37// - visit the protected area using the authorized token38//39// curl -s \40// -w '\n' \41// -H 'Content-Type: application/json' \42// -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjEwMDAwMDAwMDAwfQ.M3LAZmrzUkXDC1q5mSzFAs_kJrwuKz3jOoDmjJ0G4gM' \43// http://localhost:3000/protected44//45// - try to visit the protected area using an invalid token46//47// curl -s \48// -w '\n' \49// -H 'Content-Type: application/json' \50// -H 'Authorization: Bearer blahblahblah' \51// http://localhost:3000/protected5253static KEYS: LazyLock<Keys> = LazyLock::new(|| {54 let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");55 Keys::new(secret.as_bytes())56});5758#[tokio::main]59async fn main() {60 tracing_subscriber::registry()61 .with(62 tracing_subscriber::EnvFilter::try_from_default_env()63 .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),64 )65 .with(tracing_subscriber::fmt::layer())66 .init();6768 let app = Router::new()69 .route("/protected", get(protected))70 .route("/authorize", post(authorize));7172 let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")73 .await74 .unwrap();75 tracing::debug!("listening on {}", listener.local_addr().unwrap());76 axum::serve(listener, app).await;77}7879async fn protected(claims: Claims) -> Result<String, AuthError> {80 // Send the protected data to the user81 Ok(format!(82 "Welcome to the protected area :)\nYour data:\n{claims}",83 ))84}8586async fn authorize(Json(payload): Json<AuthPayload>) -> Result<Json<AuthBody>, AuthError> {87 // Check if the user sent the credentials88 if payload.client_id.is_empty() || payload.client_secret.is_empty() {89 return Err(AuthError::MissingCredentials);90 }91 // Here you can check the user credentials from a database92 if payload.client_id != "foo" || payload.client_secret != "bar" {93 return Err(AuthError::WrongCredentials);94 }95 let claims = Claims {96 sub: "b@b.com".to_owned(),97 company: "ACME".to_owned(),98 // Mandatory expiry time as UTC timestamp99 exp: 2000000000, // May 2033100 };101 // Create the authorization token102 let token = encode(&Header::default(), &claims, &KEYS.encoding)103 .map_err(|_| AuthError::TokenCreation)?;104105 // Send the authorized token106 Ok(Json(AuthBody::new(token)))107}108109impl Display for Claims {110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {111 write!(f, "Email: {}\nCompany: {}", self.sub, self.company)112 }113}114115impl AuthBody {116 fn new(access_token: String) -> Self {117 Self {118 access_token,119 token_type: "Bearer".to_string(),120 }121 }122}123124impl<S> FromRequestParts<S> for Claims125where126 S: Send + Sync,127{128 type Rejection = AuthError;129130 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {131 // Extract the token from the authorization header132 let TypedHeader(Authorization(bearer)) = parts133 .extract::<TypedHeader<Authorization<Bearer>>>()134 .await135 .map_err(|_| AuthError::InvalidToken)?;136 // Decode the user data137 let token_data = decode::<Claims>(bearer.token(), &KEYS.decoding, &Validation::default())138 .map_err(|_| AuthError::InvalidToken)?;139140 Ok(token_data.claims)141 }142}143144impl IntoResponse for AuthError {145 fn into_response(self) -> Response {146 let (status, error_message) = match self {147 AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, "Wrong credentials"),148 AuthError::MissingCredentials => (StatusCode::BAD_REQUEST, "Missing credentials"),149 AuthError::TokenCreation => (StatusCode::INTERNAL_SERVER_ERROR, "Token creation error"),150 AuthError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token"),151 };152 let body = Json(json!({153 "error": error_message,154 }));155 (status, body).into_response()156 }157}158159struct Keys {160 encoding: EncodingKey,161 decoding: DecodingKey,162}163164impl Keys {165 fn new(secret: &[u8]) -> Self {166 Self {167 encoding: EncodingKey::from_secret(secret),168 decoding: DecodingKey::from_secret(secret),169 }170 }171}172173#[derive(Debug, Clone, Serialize, Deserialize)]174struct Claims {175 sub: String,176 company: String,177 exp: usize,178}179180#[derive(Debug, Serialize)]181struct AuthBody {182 access_token: String,183 token_type: String,184}185186#[derive(Debug, Deserialize)]187struct AuthPayload {188 client_id: String,189 client_secret: String,190}191192#[derive(Debug)]193enum AuthError {194 WrongCredentials,195 MissingCredentials,196 TokenCreation,197 InvalidToken,198}