mirror of
https://github.com/TECHNOFAB11/jwt-authorizer.git
synced 2025-12-11 23:50:07 +01:00
feat: oidc issuer
This commit is contained in:
parent
d8fb138d46
commit
43f2523ec6
9 changed files with 117 additions and 29 deletions
|
|
@ -24,12 +24,16 @@ GET http://localhost:3000/api/protected
|
|||
Content-Type: application/json
|
||||
Authorization: Bearer blablabla.xxxx.xxxx
|
||||
|
||||
### discovery
|
||||
GET http://localhost:3001/.well-known/openid-configuration
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET http://localhost:3000/oidc/jwks
|
||||
|
||||
### jwks
|
||||
GET http://localhost:3001/jwks
|
||||
Content-Type: application/json
|
||||
|
||||
|
||||
###
|
||||
GET http://localhost:3000/oidc/tokens
|
||||
GET http://localhost:3001/tokens
|
||||
Content-Type: application/json
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
use axum::{
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use jwt_authorizer::{AuthError, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
|
||||
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 tower_http::trace::TraceLayer;
|
||||
|
|
@ -12,7 +9,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
|||
mod oidc_provider;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
async fn main() -> Result<(), InitError> {
|
||||
tracing_subscriber::registry()
|
||||
.with(tracing_subscriber::EnvFilter::new(
|
||||
std::env::var("RUST_LOG").unwrap_or_else(|_| "info,axum_poc=debug,tower_http=debug".into()),
|
||||
|
|
@ -26,9 +23,13 @@ async fn main() {
|
|||
u.sub.contains('@') // must be an email
|
||||
}
|
||||
|
||||
// starting oidc provider (discovery is needed by from_oidc())
|
||||
oidc_provider::run_server();
|
||||
|
||||
// First let's create an authorizer builder from a JWKS Endpoint
|
||||
// User is a struct deserializable from JWT claims representing the authorized user
|
||||
let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_jwks_url("http://localhost:3000/oidc/jwks")
|
||||
// let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc("https://accounts.google.com/")
|
||||
let jwt_auth: JwtAuthorizer<User> = JwtAuthorizer::from_oidc("http://localhost:3001")
|
||||
// .no_refresh()
|
||||
.refresh(Refresh {
|
||||
strategy: RefreshStrategy::Interval,
|
||||
|
|
@ -36,18 +37,15 @@ async fn main() {
|
|||
})
|
||||
.check(claim_checker);
|
||||
|
||||
let oidc = Router::new()
|
||||
.route("/authorize", post(oidc_provider::authorize))
|
||||
.route("/jwks", get(oidc_provider::jwks))
|
||||
.route("/tokens", get(oidc_provider::tokens));
|
||||
|
||||
// actual router demo
|
||||
let api = Router::new()
|
||||
.route("/protected", get(protected))
|
||||
.layer(jwt_auth.layer().unwrap());
|
||||
// adding the authorizer layer
|
||||
.layer(jwt_auth.layer().await?);
|
||||
// .layer(jwt_auth.check_claims(|_: User| true));
|
||||
|
||||
let app = Router::new()
|
||||
.nest("/oidc/", oidc)
|
||||
// actual protected apis
|
||||
.nest("/api", api)
|
||||
.layer(TraceLayer::new_for_http());
|
||||
|
||||
|
|
@ -55,6 +53,8 @@ async fn main() {
|
|||
tracing::info!("listening on {}", addr);
|
||||
|
||||
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ use axum::{
|
|||
headers::{authorization::Bearer, Authorization},
|
||||
http::{request::Parts, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use josekit::jwk::{
|
||||
alg::{ec::EcCurve, ec::EcKeyPair, ed::EdKeyPair, rsa::RsaKeyPair},
|
||||
|
|
@ -14,7 +15,7 @@ use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header,
|
|||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::fmt::Display;
|
||||
use std::{fmt::Display, net::SocketAddr, thread, time::Duration};
|
||||
|
||||
pub static KEYS: Lazy<Keys> = Lazy::new(|| {
|
||||
//let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
||||
|
|
@ -22,6 +23,8 @@ pub static KEYS: Lazy<Keys> = Lazy::new(|| {
|
|||
Keys::load_rsa()
|
||||
});
|
||||
|
||||
const ISSUER_URI: &str = "http://localhost:3001";
|
||||
|
||||
pub struct Keys {
|
||||
pub alg: Algorithm,
|
||||
pub encoding: EncodingKey,
|
||||
|
|
@ -38,6 +41,23 @@ impl Keys {
|
|||
}
|
||||
}
|
||||
|
||||
/// OpenId Connect discovery (simplified for test purposes)
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct OidcDiscovery {
|
||||
issuer: String,
|
||||
jwks_uri: String,
|
||||
authorization_endpoint: String,
|
||||
}
|
||||
|
||||
pub async fn discovery() -> Json<Value> {
|
||||
let d = OidcDiscovery {
|
||||
issuer: ISSUER_URI.to_owned(),
|
||||
jwks_uri: format!("{}/jwks", ISSUER_URI),
|
||||
authorization_endpoint: format!("{}/authorize", ISSUER_URI),
|
||||
};
|
||||
Json(json!(d))
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
struct JwkSet {
|
||||
keys: Vec<Jwk>,
|
||||
|
|
@ -108,6 +128,7 @@ fn build_header(alg: Algorithm, kid: &str) -> Header {
|
|||
}
|
||||
}
|
||||
|
||||
/// issues test tokens (this is not a standard endpoint)
|
||||
pub async fn tokens() -> Json<Value> {
|
||||
let claims = Claims {
|
||||
sub: "b@b.com".to_owned(),
|
||||
|
|
@ -150,6 +171,24 @@ pub async fn authorize(Json(payload): Json<AuthPayload>) -> Result<Json<AuthBody
|
|||
Ok(Json(AuthBody::new(token)))
|
||||
}
|
||||
|
||||
/// exposes oidc "like" endpoints (this is for test purposes)
|
||||
pub fn run_server() {
|
||||
// oidc "like" endpoints for test purposes
|
||||
let app = Router::new()
|
||||
.route("/.well-known/openid-configuration", get(discovery))
|
||||
.route("/authorize", post(authorize))
|
||||
.route("/jwks", get(jwks))
|
||||
.route("/tokens", get(tokens));
|
||||
|
||||
tokio::spawn(async move {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
|
||||
tracing::info!("oidc provider starting on: {}", addr);
|
||||
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
|
||||
});
|
||||
|
||||
thread::sleep(Duration::from_millis(200)); // waiting oidc to start
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Claims {
|
||||
sub: String,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue