summaryrefslogtreecommitdiff
path: root/src/extractors
diff options
context:
space:
mode:
authorniliara-edu <nil.jimeno@estudiant.fjaverianas.com>2025-01-23 23:28:01 +0100
committerniliara-edu <nil.jimeno@estudiant.fjaverianas.com>2025-01-23 23:28:01 +0100
commit8c4de2ddac066a072f376e9f30409b114aa9978c (patch)
treec1dc334904206f1b796d753293cb0b5c838f35d8 /src/extractors
parent6a7a49fb3804d0d27bbaee08b6feb26b4973b4bc (diff)
finished jws tutorial
Diffstat (limited to 'src/extractors')
-rw-r--r--src/extractors/auth_token.rs43
-rw-r--r--src/extractors/mod.rs1
2 files changed, 44 insertions, 0 deletions
diff --git a/src/extractors/auth_token.rs b/src/extractors/auth_token.rs
new file mode 100644
index 0000000..c505fdf
--- /dev/null
+++ b/src/extractors/auth_token.rs
@@ -0,0 +1,43 @@
+use std::future::{ Ready, ready };
+use actix_web::{web, FromRequest, Error as ActixWebError, HttpRequest, dev::Payload, http, http::header::HeaderValue, error::ErrorUnauthorized};
+use serde::{Serialize, Deserialize};
+use jsonwebtoken:: {decode, DecodingKey, errors::Error as JwtError, Algorithm, Validation, TokenData};
+use crate::auth::Claims;
+use crate::AppState;
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct AuthenticationToken {
+ pub id: usize,
+}
+
+impl FromRequest for AuthenticationToken {
+ type Error = ActixWebError;
+ type Future = Ready<Result<Self, Self::Error>>;
+
+ fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
+ // get auth token from the authorization header
+ let auth_header: Option<&HeaderValue> = req.headers().get(http::header::AUTHORIZATION);
+ let auth_token: String = auth_header.unwrap().to_str().unwrap_or("").to_string(); // check errors later
+ // stop empty and weird (ascii, chinese...) auth_token strings:
+ if auth_token.is_empty() { return ready(Err(ErrorUnauthorized("Invalid auth token!")))}
+ let secret: String = req.app_data::<web::Data<AppState>>().unwrap().secret.to_string();
+
+ // decode token with secret
+ let decode: Result<TokenData<Claims>, JwtError> = decode::<Claims>(
+ &auth_token,
+ &DecodingKey::from_secret(secret.as_str().as_ref()),
+ &Validation::new(Algorithm::HS256),
+ );
+
+ println!("{}", auth_token);
+ // return authenticationtoken
+ match decode {
+ Ok(token) => ready(Ok(AuthenticationToken { id: token.claims.id })),
+ Err(_) => ready(Err(ErrorUnauthorized("Unauthorized!"))),
+ }
+ }
+}
+
+/* Example execution in curl:
+curl localhost:8000/auth/protected -H "Accept: application/json" -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzY5MjAyNjU1fQ.QbWkgjmbmMwLJnia6vd67EfRkf6y-4nw572g-Nk0BOE"
+*/
diff --git a/src/extractors/mod.rs b/src/extractors/mod.rs
new file mode 100644
index 0000000..403a6a8
--- /dev/null
+++ b/src/extractors/mod.rs
@@ -0,0 +1 @@
+pub mod auth_token;