actix_jwt_auth_middleware/lib.rs
1/*!
2This crate builds upon the [`jwt-compact`](https://github.com/slowli/jwt-compact) crate
3to provide a jwt authentication middleware for the [`actix-web`](https://github.com/actix/actix-web) framework.
4
5The jwt implementation supports the revocation for tokens via `access` and `refresh` tokens.
6
7It provides multiple cryptographic signing and verifying algorithms such as `HS256`, `HS384`, `HS512`, `EdDSA` and `ES256`.
8For more infos on that mater please refer to the [`Supported algorithms`](https://docs.rs/jwt-compact/latest/jwt_compact/#supported-algorithms) section of the [`jwt-compact`](https://github.com/slowli/jwt-compact) crate.
9
10# Features
11- easy use of custom jwt claims
12- automatic extraction of the custom claims
13- extraction of tokens from `query` parameters, `HTTP` headers, [`Authorization`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) header and `cookies`
14- verify only mode (`public key` only)
15- automatic renewal of `access` token (very customizable)
16- easy way to set expiration time of `access` and `refresh` tokens
17- simple `UseJWT` trait for protecting a `App` or `Scope` (`Resource` is currently experimental [#91611](https://github.com/rust-lang/rust/issues/91611))
18- refresh authorizer function that has access to application state
19
20# Automatic Extraction of Claims
21This crate tightly integrates into the actix-web ecosystem,
22this makes it easy to Automatic extract the jwt claims from a valid token.
23```
24# use actix_jwt_auth_middleware::{FromRequest};
25# use actix_web::{get, Responder};
26# use serde::{Deserialize, Serialize};
27#[derive(Serialize, Deserialize, Clone, FromRequest)]
28struct UserClaims {
29 id: u32,
30 role: Role,
31}
32#[derive(Serialize, Deserialize, Clone, Debug)]
33enum Role {
34 Admin,
35 RegularUser,
36}
37#[get("/hello")]
38async fn hello(user_claims: UserClaims) -> impl Responder {
39 format!(
40 "Hello user with id: {}, i see you are a {:?}!",
41 user_claims.id, user_claims.role
42 )
43}
44```
45For this your custom claim type has to implement the [`FromRequest`](actix_web::FromRequest) trait
46or it has to be annotated with the `#[derive(actix-jwt-auth-middleware::FromRequest)]` macro which implements this trait for your type.
47
48# Simple Example
49```no_run
50# use actix_jwt_auth_middleware::use_jwt::UseJWTOnApp;
51# use actix_jwt_auth_middleware::{AuthResult, Authority, FromRequest, TokenSigner};
52# use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
53# use ed25519_compact::KeyPair;
54# use jwt_compact::alg::Ed25519;
55# use serde::{Deserialize, Serialize};
56#[derive(Serialize, Deserialize, Clone, Debug, FromRequest)]
57struct User {
58 id: u32,
59}
60
61#[actix_web::main]
62async fn main() -> Result<(), Box<dyn std::error::Error>> {
63 let KeyPair {
64 pk: public_key,
65 sk: secret_key,
66 } = KeyPair::generate();
67
68
69 HttpServer::new(move || {
70 let authority = Authority::<User, Ed25519, _, _>::new()
71 .refresh_authorizer(|| async move { Ok(()) })
72 .token_signer(Some(
73 TokenSigner::new()
74 .signing_key(secret_key.clone())
75 .algorithm(Ed25519)
76 .build()
77 .expect(""),
78 ))
79 .verifying_key(public_key)
80 .build()
81 .expect("");
82
83 App::new()
84 .service(login)
85 .use_jwt(authority, web::scope("").service(hello))
86 })
87 .bind(("127.0.0.1", 8080))?
88 .run()
89 .await?;
90
91 Ok(())
92}
93
94#[get("/login")]
95async fn login(token_signer: web::Data<TokenSigner<User, Ed25519>>) -> AuthResult<HttpResponse> {
96 let user = User { id: 1 };
97 Ok(HttpResponse::Ok()
98 .cookie(token_signer.create_access_cookie(&user)?)
99 .cookie(token_signer.create_refresh_cookie(&user)?)
100 .body("You are now logged in"))
101}
102
103#[get("/hello")]
104async fn hello(user: User) -> impl Responder {
105 format!("Hello there, i see your user id is {}.", user.id)
106}
107```
108For more examples please referee to the `examples` directory.
109*/
110
111#[doc(inline)]
112pub use actix_jwt_auth_middleware_derive::FromRequest;
113pub use authority::*;
114pub use errors::*;
115pub use middleware::*;
116pub use token_signer::*;
117
118mod authority;
119mod errors;
120mod helper_macros;
121mod middleware;
122mod token_signer;
123/// Convenience `UseJWT` traits
124pub mod use_jwt;
125mod validate;