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
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
AuthGuardwhich 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
- Auth
State - Holds the authentication state used by the application.
- Localized
Claim - Represents a localized claim value, such as a name or address that may have an associated language.
- OIDC
Config - OIDC
Guard - Guard type used in Rocket request handling that holds validated JWT claims and fetched user info.
- Pronoun
Claim - User
Info - Basic user profile information returned from the userinfo endpoint.
Enums§
- Error
- Top-level error type for the authentication layer.
- User
Info Err - Errors that can occur when parsing or converting user info claims.
Traits§
- Core
Claims - 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.