JWT Authentication and token generation

This commit is contained in:
Ara Sadoyan
2025-04-17 15:15:34 +02:00
parent 497f07ccce
commit 34d86c374a
11 changed files with 284 additions and 45 deletions

View File

@@ -1,3 +1,4 @@
use crate::utils::jwt::check_jwt;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use pingora_proxy::Session;
@@ -7,6 +8,7 @@ trait AuthValidator {
}
struct BasicAuth<'a>(&'a str);
struct ApiKeyAuth<'a>(&'a str);
struct JwtAuth<'a>(&'a str);
impl AuthValidator for BasicAuth<'_> {
fn validate(&self, session: &Session) -> bool {
@@ -30,6 +32,16 @@ impl AuthValidator for ApiKeyAuth<'_> {
}
}
impl AuthValidator for JwtAuth<'_> {
fn validate(&self, session: &Session) -> bool {
let jwtsecret = self.0;
if let Some(header) = session.get_header("x-jwt-token") {
let tok = header.to_str().ok().unwrap();
return check_jwt(tok, jwtsecret);
}
false
}
}
fn validate(auth: &dyn AuthValidator, session: &Session) -> bool {
auth.validate(session)
}
@@ -44,6 +56,10 @@ pub fn authenticate(c: &[String], session: &Session) -> bool {
let auth = ApiKeyAuth(c[1].as_str().into());
validate(&auth, session)
}
"jwt" => {
let auth = JwtAuth(c[1].as_str().into());
validate(&auth, session)
}
_ => {
println!("Unsupported authentication mechanism : {}", c[0]);
false