mirror of
https://github.com/TECHNOFAB11/jwt-authorizer.git
synced 2025-12-12 08:00: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
|
Content-Type: application/json
|
||||||
Authorization: Bearer blablabla.xxxx.xxxx
|
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
|
Content-Type: application/json
|
||||||
|
|
||||||
|
|
||||||
###
|
###
|
||||||
GET http://localhost:3000/oidc/tokens
|
GET http://localhost:3001/tokens
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,5 @@
|
||||||
use axum::{
|
use axum::{routing::get, Router};
|
||||||
routing::{get, post},
|
use jwt_authorizer::{error::InitError, AuthError, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
|
||||||
Router,
|
|
||||||
};
|
|
||||||
use jwt_authorizer::{AuthError, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::{fmt::Display, net::SocketAddr};
|
use std::{fmt::Display, net::SocketAddr};
|
||||||
use tower_http::trace::TraceLayer;
|
use tower_http::trace::TraceLayer;
|
||||||
|
|
@ -12,7 +9,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
mod oidc_provider;
|
mod oidc_provider;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() -> Result<(), InitError> {
|
||||||
tracing_subscriber::registry()
|
tracing_subscriber::registry()
|
||||||
.with(tracing_subscriber::EnvFilter::new(
|
.with(tracing_subscriber::EnvFilter::new(
|
||||||
std::env::var("RUST_LOG").unwrap_or_else(|_| "info,axum_poc=debug,tower_http=debug".into()),
|
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
|
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
|
// First let's create an authorizer builder from a JWKS Endpoint
|
||||||
// User is a struct deserializable from JWT claims representing the authorized user
|
// 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()
|
// .no_refresh()
|
||||||
.refresh(Refresh {
|
.refresh(Refresh {
|
||||||
strategy: RefreshStrategy::Interval,
|
strategy: RefreshStrategy::Interval,
|
||||||
|
|
@ -36,18 +37,15 @@ async fn main() {
|
||||||
})
|
})
|
||||||
.check(claim_checker);
|
.check(claim_checker);
|
||||||
|
|
||||||
let oidc = Router::new()
|
// actual router demo
|
||||||
.route("/authorize", post(oidc_provider::authorize))
|
|
||||||
.route("/jwks", get(oidc_provider::jwks))
|
|
||||||
.route("/tokens", get(oidc_provider::tokens));
|
|
||||||
|
|
||||||
let api = Router::new()
|
let api = Router::new()
|
||||||
.route("/protected", get(protected))
|
.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));
|
// .layer(jwt_auth.check_claims(|_: User| true));
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.nest("/oidc/", oidc)
|
// actual protected apis
|
||||||
.nest("/api", api)
|
.nest("/api", api)
|
||||||
.layer(TraceLayer::new_for_http());
|
.layer(TraceLayer::new_for_http());
|
||||||
|
|
||||||
|
|
@ -55,6 +53,8 @@ async fn main() {
|
||||||
tracing::info!("listening on {}", addr);
|
tracing::info!("listening on {}", addr);
|
||||||
|
|
||||||
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
|
axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
|
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,8 @@ use axum::{
|
||||||
headers::{authorization::Bearer, Authorization},
|
headers::{authorization::Bearer, Authorization},
|
||||||
http::{request::Parts, StatusCode},
|
http::{request::Parts, StatusCode},
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
Json,
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
};
|
};
|
||||||
use josekit::jwk::{
|
use josekit::jwk::{
|
||||||
alg::{ec::EcCurve, ec::EcKeyPair, ed::EdKeyPair, rsa::RsaKeyPair},
|
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 once_cell::sync::Lazy;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{json, Value};
|
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(|| {
|
pub static KEYS: Lazy<Keys> = Lazy::new(|| {
|
||||||
//let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
//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()
|
Keys::load_rsa()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const ISSUER_URI: &str = "http://localhost:3001";
|
||||||
|
|
||||||
pub struct Keys {
|
pub struct Keys {
|
||||||
pub alg: Algorithm,
|
pub alg: Algorithm,
|
||||||
pub encoding: EncodingKey,
|
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)]
|
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||||
struct JwkSet {
|
struct JwkSet {
|
||||||
keys: Vec<Jwk>,
|
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> {
|
pub async fn tokens() -> Json<Value> {
|
||||||
let claims = Claims {
|
let claims = Claims {
|
||||||
sub: "b@b.com".to_owned(),
|
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)))
|
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)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
struct Claims {
|
struct Claims {
|
||||||
sub: String,
|
sub: String,
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ JWT authoriser Layer for Axum.
|
||||||
|
|
||||||
// adding the authorization layer
|
// adding the authorization layer
|
||||||
let app = Router::new().route("/protected", get(protected))
|
let app = Router::new().route("/protected", get(protected))
|
||||||
.layer(jwt_auth.layer().unwrap());
|
.layer(jwt_auth.layer().await.unwrap());
|
||||||
|
|
||||||
// proteced handler with user injection (mapping some jwt claims)
|
// proteced handler with user injection (mapping some jwt claims)
|
||||||
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
|
async fn protected(JwtClaims(user): JwtClaims<User>) -> Result<String, AuthError> {
|
||||||
|
|
|
||||||
|
|
@ -51,12 +51,14 @@ pub enum KeySourceType {
|
||||||
ED(String),
|
ED(String),
|
||||||
Secret(&'static str),
|
Secret(&'static str),
|
||||||
Jwks(String),
|
Jwks(String),
|
||||||
|
Discovery(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C> Authorizer<C>
|
impl<C> Authorizer<C>
|
||||||
where
|
where
|
||||||
C: DeserializeOwned + Clone + Send + Sync,
|
C: DeserializeOwned + Clone + Send + Sync,
|
||||||
{
|
{
|
||||||
|
// TODO: expose it in JwtAuthorizer
|
||||||
pub fn from_jwks(jwks: &str, claims_checker: Option<FnClaimsChecker<C>>) -> Result<Authorizer<C>, AuthError> {
|
pub fn from_jwks(jwks: &str, claims_checker: Option<FnClaimsChecker<C>>) -> Result<Authorizer<C>, AuthError> {
|
||||||
let set: JwkSet = serde_json::from_str(jwks)?;
|
let set: JwkSet = serde_json::from_str(jwks)?;
|
||||||
let k = DecodingKey::from_jwk(&set.keys[0])?;
|
let k = DecodingKey::from_jwk(&set.keys[0])?;
|
||||||
|
|
@ -76,7 +78,7 @@ where
|
||||||
KeySourceType::EC(path) => DecodingKey::from_ec_der(&read_data(path.as_str())?),
|
KeySourceType::EC(path) => DecodingKey::from_ec_der(&read_data(path.as_str())?),
|
||||||
KeySourceType::ED(path) => DecodingKey::from_ed_der(&read_data(path.as_str())?),
|
KeySourceType::ED(path) => DecodingKey::from_ed_der(&read_data(path.as_str())?),
|
||||||
KeySourceType::Secret(secret) => DecodingKey::from_secret(secret.as_bytes()),
|
KeySourceType::Secret(secret) => DecodingKey::from_secret(secret.as_bytes()),
|
||||||
KeySourceType::Jwks(_) => panic!("bug: use from_jwks_url() to initialise Authorizer"), // should never hapen
|
_ => panic!("bug: use from_jwks_url() or from_oidc() to initialise Authorizer"), // should never hapen
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Authorizer {
|
Ok(Authorizer {
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,9 @@ pub enum InitError {
|
||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
KeyFileDecodingError(#[from] jsonwebtoken::errors::Error),
|
KeyFileDecodingError(#[from] jsonwebtoken::errors::Error),
|
||||||
|
|
||||||
|
#[error("Builder Error {0}")]
|
||||||
|
DiscoveryError(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ use tower_service::Service;
|
||||||
use crate::authorizer::{Authorizer, FnClaimsChecker, KeySourceType};
|
use crate::authorizer::{Authorizer, FnClaimsChecker, KeySourceType};
|
||||||
use crate::error::InitError;
|
use crate::error::InitError;
|
||||||
use crate::jwks::key_store_manager::Refresh;
|
use crate::jwks::key_store_manager::Refresh;
|
||||||
use crate::{AuthError, RefreshStrategy};
|
use crate::{oidc, AuthError, RefreshStrategy};
|
||||||
|
|
||||||
/// Authorizer Layer builder
|
/// Authorizer Layer builder
|
||||||
///
|
///
|
||||||
|
|
@ -37,7 +37,16 @@ impl<C> JwtAuthorizer<C>
|
||||||
where
|
where
|
||||||
C: Clone + DeserializeOwned + Send + Sync,
|
C: Clone + DeserializeOwned + Send + Sync,
|
||||||
{
|
{
|
||||||
/// Build Authorizer Layer from a JWKS endpoint
|
/// Builds Authorizer Layer from a OpenId Connect discover metadata
|
||||||
|
pub fn from_oidc(issuer: &str) -> JwtAuthorizer<C> {
|
||||||
|
JwtAuthorizer {
|
||||||
|
key_source_type: Some(KeySourceType::Discovery(issuer.to_string())),
|
||||||
|
refresh: Default::default(),
|
||||||
|
claims_checker: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds Authorizer Layer from a JWKS endpoint
|
||||||
pub fn from_jwks_url(url: &'static str) -> JwtAuthorizer<C> {
|
pub fn from_jwks_url(url: &'static str) -> JwtAuthorizer<C> {
|
||||||
JwtAuthorizer {
|
JwtAuthorizer {
|
||||||
key_source_type: Some(KeySourceType::Jwks(url.to_owned())),
|
key_source_type: Some(KeySourceType::Jwks(url.to_owned())),
|
||||||
|
|
@ -46,7 +55,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build Authorizer Layer from a RSA PEM file
|
/// Builds Authorizer Layer from a RSA PEM file
|
||||||
pub fn from_rsa_pem(path: &'static str) -> JwtAuthorizer<C> {
|
pub fn from_rsa_pem(path: &'static str) -> JwtAuthorizer<C> {
|
||||||
JwtAuthorizer {
|
JwtAuthorizer {
|
||||||
key_source_type: Some(KeySourceType::RSA(path.to_owned())),
|
key_source_type: Some(KeySourceType::RSA(path.to_owned())),
|
||||||
|
|
@ -55,7 +64,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build Authorizer Layer from a EC PEM file
|
/// Builds Authorizer Layer from a EC PEM file
|
||||||
pub fn from_ec_pem(path: &'static str) -> JwtAuthorizer<C> {
|
pub fn from_ec_pem(path: &'static str) -> JwtAuthorizer<C> {
|
||||||
JwtAuthorizer {
|
JwtAuthorizer {
|
||||||
key_source_type: Some(KeySourceType::EC(path.to_owned())),
|
key_source_type: Some(KeySourceType::EC(path.to_owned())),
|
||||||
|
|
@ -64,7 +73,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build Authorizer Layer from a EC PEM file
|
/// Builds Authorizer Layer from a EC PEM file
|
||||||
pub fn from_ed_pem(path: &'static str) -> JwtAuthorizer<C> {
|
pub fn from_ed_pem(path: &'static str) -> JwtAuthorizer<C> {
|
||||||
JwtAuthorizer {
|
JwtAuthorizer {
|
||||||
key_source_type: Some(KeySourceType::ED(path.to_owned())),
|
key_source_type: Some(KeySourceType::ED(path.to_owned())),
|
||||||
|
|
@ -73,7 +82,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build Authorizer Layer from a secret phrase
|
/// Builds Authorizer Layer from a secret phrase
|
||||||
pub fn from_secret(secret: &'static str) -> JwtAuthorizer<C> {
|
pub fn from_secret(secret: &'static str) -> JwtAuthorizer<C> {
|
||||||
JwtAuthorizer {
|
JwtAuthorizer {
|
||||||
key_source_type: Some(KeySourceType::Secret(secret)),
|
key_source_type: Some(KeySourceType::Secret(secret)),
|
||||||
|
|
@ -82,7 +91,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// refresh configuration for jwk store
|
/// Refreshes configuration for jwk store
|
||||||
pub fn refresh(mut self, refresh: Refresh) -> JwtAuthorizer<C> {
|
pub fn refresh(mut self, refresh: Refresh) -> JwtAuthorizer<C> {
|
||||||
if self.refresh.is_some() {
|
if self.refresh.is_some() {
|
||||||
tracing::warn!("More than one refresh configuration found!");
|
tracing::warn!("More than one refresh configuration found!");
|
||||||
|
|
@ -112,7 +121,7 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build axum layer
|
/// Build axum layer
|
||||||
pub fn layer(&self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
pub async fn layer(&self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
||||||
let auth = if let Some(ref key_source_type) = self.key_source_type {
|
let auth = if let Some(ref key_source_type) = self.key_source_type {
|
||||||
match key_source_type {
|
match key_source_type {
|
||||||
KeySourceType::RSA(_) | KeySourceType::EC(_) | KeySourceType::ED(_) | KeySourceType::Secret(_) => {
|
KeySourceType::RSA(_) | KeySourceType::EC(_) | KeySourceType::ED(_) | KeySourceType::Secret(_) => {
|
||||||
|
|
@ -123,6 +132,14 @@ where
|
||||||
self.claims_checker.clone(),
|
self.claims_checker.clone(),
|
||||||
self.refresh.unwrap_or_default(),
|
self.refresh.unwrap_or_default(),
|
||||||
)?),
|
)?),
|
||||||
|
KeySourceType::Discovery(issuer_url) => {
|
||||||
|
let jwks_url = oidc::discover_jwks(issuer_url).await?;
|
||||||
|
Arc::new(Authorizer::from_jwks_url(
|
||||||
|
&jwks_url,
|
||||||
|
self.claims_checker.clone(),
|
||||||
|
self.refresh.unwrap_or_default(),
|
||||||
|
)?)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err(InitError::BuilderError(
|
return Err(InitError::BuilderError(
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ pub mod authorizer;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod jwks;
|
pub mod jwks;
|
||||||
pub mod layer;
|
pub mod layer;
|
||||||
|
mod oidc;
|
||||||
|
|
||||||
/// Claims serialized using T
|
/// Claims serialized using T
|
||||||
#[derive(Debug, Clone, Copy, Default)]
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
|
|
||||||
22
jwt-authorizer/src/oidc.rs
Normal file
22
jwt-authorizer/src/oidc.rs
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::error::InitError;
|
||||||
|
|
||||||
|
/// OpenId Connect discovery (simplified for test purposes)
|
||||||
|
#[derive(Deserialize, Clone)]
|
||||||
|
pub struct OidcDiscovery {
|
||||||
|
pub jwks_uri: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn discover_jwks(issuer: &str) -> Result<String, InitError> {
|
||||||
|
let discovery_url = format!("{}/.well-known/openid-configuration", issuer);
|
||||||
|
reqwest::Client::new()
|
||||||
|
.get(discovery_url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| InitError::DiscoveryError(e.to_string()))?
|
||||||
|
.json::<OidcDiscovery>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| InitError::DiscoveryError(e.to_string()))
|
||||||
|
.map(|d| d.jwks_uri)
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue