Crate rocket_oidc

Crate rocket_oidc 

Source
Expand description
use serde_derive::{Serialize, Deserialize};
use rocket::{catch, catchers, routes, launch, get};
use rocket::Build;
use rocket::State;
use rocket::fs::FileServer;
use rocket::response::{Redirect, content::RawHtml};
use rocket_oidc::{OIDCConfig, CoreClaims, OIDCGuard};

#[non_exhaustive]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserGuard {
    pub email: String,
    pub sub: String,
    pub picture: Option<String>,
    pub email_verified: Option<bool>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserClaims {
    guard: UserGuard,
    pub iss: String,
    pub aud: String,
    exp: i64,
    iat: i64,
}

impl CoreClaims for UserClaims {
    fn subject(&self) -> &str {
        self.guard.sub.as_str()
    }

    fn issuer(&self) -> &str {
        self.iss.as_str()
    }

    fn audience(&self) -> &str {
        self.aud.as_str()
    }

    fn issued_at(&self) -> i64 {
        self.iat
    }

    fn expiration(&self) -> i64 {
        self.exp
    }
}

pub type Guard = OIDCGuard<UserClaims>;

#[catch(401)]
fn unauthorized() -> Redirect {
    Redirect::to("/")
}

#[get("/")]
async fn index() -> RawHtml<String> {
    RawHtml(format!("<h1>Hello World</h1>"))
}

#[get("/protected")]
async fn protected(guard: Guard) -> RawHtml<String> {
    let userinfo = guard.userinfo;
    RawHtml(format!("<h1>Hello {} {}</h1>", userinfo.given_name(), userinfo.family_name()))
}

#[launch]
async fn rocket() -> rocket::Rocket<Build> {
    let mut rocket = rocket::build()
        .mount("/", routes![index])
        .register("/", catchers![unauthorized]);
    let config = OIDCConfig::from_env().unwrap();
    rocket_oidc::setup(rocket, config)
        .await
        .unwrap()
}

§Auth Only

you can use an AuthGuard type which only validates the claims in the json web token and doesn’t rely on a full OIDC implementation

use rocket_oidc::OIDCConfig;
use rocket::{catchers, routes, catch, launch, get};
use jsonwebtoken::DecodingKey;

#[get("/")]
async fn index() -> &'static str {
    "Hello, world!"
}

#[catch(401)]
fn unauthorized() -> &'static str {
    "Unauthorized"
}

#[launch]
async fn rocket() -> rocket::Rocket<rocket::Build> {
    let config = OIDCConfig::from_env().unwrap();
    let decoding_key: DecodingKey = DecodingKey::from_rsa_pem(include_str!("public.pem").as_bytes()).ok().unwrap();

        let validator = rocket_oidc::client::Validator::from_pubkey(
            config.issuer_url.to_string(),
            "storyteller".to_string(),
            "RS256".to_string(),
            decoding_key,
        )
        .unwrap();
    let mut rocket = rocket::build()
        .mount("/", routes![index])
        .manage(validator)
        .register("/", catchers![unauthorized]);

    rocket
}

Modules§

auth
This module provides AuthGuard which doesn’t request user info, but simply validates server public key this is useful for implementing local only login systems that don’t rely on full OIDC support from the authorization server
client
routes
sign
Utilities for acting as an OIDC token signer. OpenID Connect (OIDC) signing utilities.
token

Structs§

AddClaims
AuthState
Holds the authentication state used by the application.
LocalizedClaim
Represents a localized claim value, such as a name or address that may have an associated language.
OIDCConfig
OIDCGuard
Guard type used in Rocket request handling that holds validated JWT claims and fetched user info.
PronounClaim
UserInfo
Basic user profile information returned from the userinfo endpoint.

Enums§

Error
Top-level error type for the authentication layer.
UserInfoErr
Errors that can occur when parsing or converting user info claims.

Traits§

CoreClaims
Trait for extracting the subject identifier from any set of claims. this is also used as a marker trait

Functions§

from_provider_oidc_config
Builds the authentication state by initializing the OIDC client and token validator from the given configuration.
login
Stores authentication cookies in the user’s browser after successful login.
setup
Initializes the Rocket application with OpenID Connect authentication support.

Type Aliases§

TokenErr