jwt-authorizer/demo-server/src/main.rs

83 lines
2.5 KiB
Rust
Raw Normal View History

2023-01-28 21:20:56 +01:00
use axum::{routing::get, Router};
use jwt_authorizer::{
error::InitError, AuthError, Authorizer, IntoLayer, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy,
};
2023-01-08 13:45:21 +01:00
use serde::Deserialize;
use tokio::net::TcpListener;
2023-01-08 13:45:21 +01:00
use tower_http::trace::TraceLayer;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod oidc_provider;
/// Object representing claims
/// (a subset of deserialized claims)
#[derive(Debug, Deserialize, Clone)]
struct User {
sub: String,
}
2023-01-08 13:45:21 +01:00
#[tokio::main]
2023-01-28 21:20:56 +01:00
async fn main() -> Result<(), InitError> {
2023-01-08 13:45:21 +01:00
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
2023-02-06 23:41:45 +01:00
std::env::var("RUST_LOG").unwrap_or_else(|_| "info,jwt_authorizer=debug,tower_http=debug".into()),
2023-01-08 13:45:21 +01:00
))
.with(tracing_subscriber::fmt::layer())
.init();
// claims checker function
2023-01-08 13:45:21 +01:00
fn claim_checker(u: &User) -> bool {
info!("checking claims: {} -> {}", u.sub, u.sub.contains('@'));
u.sub.contains('@') // must be an email
}
2023-01-28 21:20:56 +01:00
// starting oidc provider (discovery is needed by from_oidc())
let issuer_uri = oidc_provider::run_server();
2023-01-28 21:20:56 +01:00
// First let's create an authorizer builder from a Oidc Discovery
2023-01-08 13:45:21 +01:00
// User is a struct deserializable from JWT claims representing the authorized user
2023-01-28 21:20:56 +01:00
// let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc("https://accounts.google.com/")
let auth: Authorizer<User> = JwtAuthorizer::from_oidc(issuer_uri)
2023-01-28 08:43:51 +01:00
// .no_refresh()
.refresh(Refresh {
strategy: RefreshStrategy::Interval,
..Default::default()
})
.check(claim_checker)
.build()
.await?;
2023-01-08 13:45:21 +01:00
2023-01-28 21:20:56 +01:00
// actual router demo
2023-01-08 13:45:21 +01:00
let api = Router::new()
.route("/protected", get(protected))
2023-01-28 21:20:56 +01:00
// adding the authorizer layer
.layer(auth.into_layer());
2023-01-08 13:45:21 +01:00
let app = Router::new()
// public endpoint
.route("/public", get(public_handler))
// protected APIs
2023-01-08 13:45:21 +01:00
.nest("/api", api)
.layer(TraceLayer::new_for_http());
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
tracing::info!("listening on {:?}", listener.local_addr());
2023-01-08 13:45:21 +01:00
axum::serve(listener, app.into_make_service()).await.unwrap();
2023-01-28 21:20:56 +01:00
Ok(())
2023-01-08 13:45:21 +01:00
}
/// handler with injected claims object
2023-01-08 13:45:21 +01:00
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
// Send the protected data to the user
Ok(format!("Welcome: {}", user.sub))
}
// public url handler
async fn public_handler() -> &'static str {
"Public URL!"
2023-01-08 13:45:21 +01:00
}