refactor: demo server (clean, refactor, docs)

This commit is contained in:
cduvray 2023-01-30 23:44:25 +01:00
parent 43f2523ec6
commit 6ff5d88ae9
5 changed files with 56 additions and 170 deletions

View file

@ -1,13 +1,20 @@
use axum::{routing::get, Router};
use jwt_authorizer::{error::InitError, AuthError, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
use serde::Deserialize;
use std::{fmt::Display, net::SocketAddr};
use std::net::SocketAddr;
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,
}
#[tokio::main]
async fn main() -> Result<(), InitError> {
tracing_subscriber::registry()
@ -17,6 +24,7 @@ async fn main() -> Result<(), InitError> {
.with(tracing_subscriber::fmt::layer())
.init();
// claims checker function
fn claim_checker(u: &User) -> bool {
info!("checking claims: {} -> {}", u.sub, u.sub.contains('@'));
@ -24,12 +32,12 @@ async fn main() -> Result<(), InitError> {
}
// starting oidc provider (discovery is needed by from_oidc())
oidc_provider::run_server();
let issuer_uri = oidc_provider::run_server();
// First let's create an authorizer builder from a JWKS Endpoint
// First let's create an authorizer builder from a Oidc Discovery
// User is a struct deserializable from JWT claims representing the authorized user
// let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc("https://accounts.google.com/")
let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc("http://localhost:3001")
let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc(issuer_uri)
// .no_refresh()
.refresh(Refresh {
strategy: RefreshStrategy::Interval,
@ -42,10 +50,11 @@ async fn main() -> Result<(), InitError> {
.route("/protected", get(protected))
// adding the authorizer layer
.layer(jwt_auth.layer().await?);
// .layer(jwt_auth.check_claims(|_: User| true));
let app = Router::new()
// actual protected apis
// public endpoint
.route("/public", get(public_handler))
// protected APIs
.nest("/api", api)
.layer(TraceLayer::new_for_http());
@ -57,18 +66,13 @@ async fn main() -> Result<(), InitError> {
Ok(())
}
/// handler with injected claims object
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
// Send the protected data to the user
Ok(format!("Welcome: {}", user.sub))
}
#[derive(Debug, Deserialize, Clone)]
struct User {
sub: String,
}
impl Display for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "User: {:?}", self.sub)
}
// public url handler
async fn public_handler() -> &'static str {
"Public URL!"
}