Authorization works

This commit is contained in:
Sebastian H. Gabrielli 2023-12-31 15:28:35 +01:00
parent 40714e4215
commit a68730ac52
3 changed files with 74 additions and 5 deletions

View File

@ -1 +0,0 @@
//use jwt_validation::*;

70
src/authorization.rs Normal file
View File

@ -0,0 +1,70 @@
// Import the Rocket requirements
use rocket::http::Status;
use rocket::request::{self, Outcome, Request, FromRequest};
// Import the jwt validation functions
mod jwt_validation {
include!("jwt_validation.rs");
}
use crate::authorization::jwt_validation::*;
#[derive(Debug)]
pub struct BoardMember {
pub username: String
}
#[derive(Debug)]
pub enum AuthenticationError {
InvalidJWT,
MissingAuthenticationHeader,
InvalidAuthenticationHeader,
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for BoardMember {
type Error = AuthenticationError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
// Extract the autorization header
let autorization_header: &str;
match req.headers().get_one("Authorization") {
Some(data) => {
autorization_header = data;
},
// Missing header, return unauthroized
None => return Outcome::Error((Status::Unauthorized, AuthenticationError::MissingAuthenticationHeader))
}
// Extract the JWT token from the authroization header
let jwt_token: &str;
match autorization_header.split("Bearer ").collect::<Vec<&str>>().get(1) {
Some(token) => jwt_token = token,
// Header is not structured correctly, return unauthroized
None => return Outcome::Error((Status::Unauthorized, AuthenticationError::InvalidAuthenticationHeader))
}
// This is temporary, this should be saved and not called on each validation
let mut jwt_info: JwtInfo;
match fetch_jwt_info("https://sso.gitgals.com/application/o/sebtest/.well-known/openid-configuration", vec!("https://sso.gitgals.com/application/o/sebtest/".into())).await {
Ok(data) => jwt_info = data,
Err(e) => {
println!("{:?}", e);
return Outcome::Error((Status::InternalServerError, AuthenticationError::InvalidJWT))
},
}
jwt_info.audience = vec!("CLaLr8sikEiN7NCrPMhjhbtLZgnZJ6JZVzPdVN5P".into());
// Validate the token and store the result
let valid_token: MyClaims;
match validate_jwt(jwt_token, &mut jwt_info).await {
Ok(data) => valid_token = data,
Err(e) => {
println!("{:?}", e);
return Outcome::Error((Status::Unauthorized, AuthenticationError::InvalidJWT))
}
}
let username = valid_token.preferred_username.unwrap().clone();
Outcome::Success(BoardMember{username})
}
}

View File

@ -16,13 +16,13 @@ use webserver_member::*;
use rocket_cors::{AllowedOrigins, CorsOptions};
// Handle authentication
mod jwt_validation;
use jwt_validation::*;
mod authorization;
use authorization::BoardMember;
// Serve the very exiting main page
#[get("/")]
fn index() -> &'static str {
"Hello, world!\nNothing useful is served here."
fn index(board_member: BoardMember) -> String {
format!("Hello, world!\nThe autorized user's preffered username is: {:?}", board_member.username)
}
#[launch]