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

View File

@@ -10,6 +10,7 @@ pub struct FromFileProvider {
}
pub struct APIUpstreamProvider {
pub address: String,
pub masterkey: String,
}
pub struct ConsulProvider {
@@ -24,7 +25,7 @@ pub trait Discovery {
#[async_trait]
impl Discovery for APIUpstreamProvider {
async fn start(&self, toreturn: Sender<Configuration>) {
webserver::run_server(self.address.clone(), toreturn).await;
webserver::run_server(self.address.clone(), self.masterkey.clone(), toreturn).await;
}
}

16
src/utils/jwt.rs Normal file
View File

@@ -0,0 +1,16 @@
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Claims {
pub(crate) user: String,
pub(crate) exp: u64,
}
pub fn check_jwt(input: &str, secret: &str) -> bool {
let validation = Validation::new(Algorithm::HS256);
let token_data = decode::<Claims>(&input, &DecodingKey::from_secret(secret.as_ref()), &validation);
match token_data {
Ok(_) => true,
Err(_) => false,
}
}