Skip to main content

Authorization

Struct Authorization 

Source
pub struct Authorization { /* private fields */ }
Expand description

Entry point of the crate: configuration plus handlers, middlewares, and helpers.

Cloning is cheap — this is an Arc handle around shared inner state.

Implementations§

Source§

impl Authorization

Source

pub async fn route<B>(&self, req: Request<B>) -> Response
where B: Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>,

Dispatches a request to the matching auth endpoint (catch-all style).

Useful for frameworks that do not merge routers (for example actix-web):

  • GET {base}/providers
  • ANY {base}/provider/{provider}
  • ANY {base}/provider/{provider}/callback
Source

pub async fn get_providers<B>(&self, req: Request<B>) -> Response
where B: Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>,

Lists the configured providers in the Auth.js-compatible shape.

Source

pub async fn handle_sign_in<B>(&self, req: Request<B>) -> Response
where B: Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>,

Starts the sign-in flow for the provider named in the path: an OAuth redirect, or a credentials POST.

Source

pub async fn handle_callback<B>(&self, req: Request<B>) -> Response
where B: Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>,

Handles the provider redirect back to this application.

Source

pub fn with_user_id(&self, user_id: &str) -> AuthorizeOptionsFunc

Sets the user the session and tokens belong to.

Source

pub fn with_user_roles(&self, roles: JsonbArray) -> AuthorizeOptionsFunc

Sets the role grants embedded in the tokens.

Source

pub fn with_content(&self, content: JsonbAny) -> AuthorizeOptionsFunc

Sets the arbitrary content embedded in the access/refresh token claims.

Source

pub fn with_account(&self, account: Account) -> AuthorizeOptionsFunc

Attaches the provider account stored on the session row.

Source

pub fn with_ip_address(&self, ip_address: &str) -> AuthorizeOptionsFunc

Records the caller’s IP address on the session row.

Source

pub fn with_user_agent(&self, user_agent: &str) -> AuthorizeOptionsFunc

Records the caller’s user agent on the session row.

Source

pub fn with_method(&self, method: &str) -> AuthorizeOptionsFunc

Records how the session was established (the provider id).

Source

pub fn session_meta_from_request( &self, r: &RequestContext<'_>, method: &str, ) -> Vec<AuthorizeOptionsFunc> ⓘ

Captures the request metadata stored on the session row.

Source§

impl Authorization

Source

pub fn new(config: Config) -> Result<Self>

Validates the configuration and returns a ready-to-use handle.

Source

pub fn new_with( config: Config, opts: impl IntoIterator<Item = ConfigFunc>, ) -> Result<Self>

Applies the given options on top of config before validating it.

Source

pub fn jwt_secret(&self) -> &str

The HMAC signing secret.

Source

pub fn auth_url(&self) -> &str

The configured external origin.

Source

pub fn signing_method(&self) -> &str

The configured JWT signing method name.

Source

pub fn access_token_duration(&self) -> &str

The configured access-token lifetime.

Source

pub fn refresh_token_duration(&self) -> &str

The configured refresh-token lifetime.

Source

pub fn sign_in_redirect_url(&self) -> &str

The configured sign-in redirect target.

Source

pub fn db(&self) -> Result<&PgPool>

The database pool, or Error::NotInitialized when none was configured.

Source

pub fn redis(&self) -> Option<&Client>

The configured Redis client, if any.

Source

pub fn redis_prefix(&self) -> &str

The Redis key prefix.

Source

pub fn redis_ttl(&self) -> Duration

The Redis session time-to-live.

Source

pub fn user_table_name(&self) -> &str

The configured users table.

Source

pub fn sessions_table(&self) -> &str

The configured sessions table.

Source

pub fn cookie_session_name(&self) -> &str

The name of the WEB session cookie.

Source

pub fn cookies(&self) -> &CookieOptions

The configured cookie overrides.

Source

pub fn providers(&self) -> &[Arc<dyn Provider>]

Every configured provider, in order.

Source

pub fn with_jwt_secret(self, jwt_secret: &str) -> Self

Overrides the signing secret.

Source

pub fn with_auth_url(self, auth_url: &str) -> Self

Overrides the external origin.

Source

pub fn with_db(self, db: PgPool) -> Self

Overrides the database pool.

Source

pub fn with_redis(self, redis: Client) -> Self

Overrides the Redis client.

Source

pub fn with_redis_prefix(self, redis_prefix: &str) -> Self

Overrides the Redis key prefix.

Source

pub fn with_redis_ttl(self, redis_ttl: Duration) -> Self

Overrides the Redis session time-to-live.

Overrides the WEB session cookie name.

Source

pub fn with_resolve_user(self, resolve_user: ResolveUserFn) -> Self

Overrides the user-resolution callback.

Source§

impl Authorization

Source

pub async fn authorize( &self, opts: impl IntoIterator<Item = AuthorizeOptionsFunc>, ) -> Result<(Tokens, String)>

Creates a fresh session row and signs an access/refresh token pair for it.

Returns the token pair and the new session id.

Source§

impl Authorization

Source

pub fn render_callback_page<T: Serialize>(&self, data: T) -> Response

Renders a small HTML page that persists the token response in localStorage under authorization-storage (matching the frontend zustand persist format) and either notifies the opener (popup flow) or redirects to the saved redirect URL (redirect flow).

Source§

impl Authorization

Source

pub fn get_claims<'a>( &self, r: &'a RequestContext<'a>, ) -> Result<&'a JsonMap<String, Value>>

Returns the claims set by the JWT middleware. It errors out if no token is present on the request.

Source§

impl Authorization

Stores the target resource id for a provider-connect OAuth round-trip.

Reads and clears the connect-resource cookie.

Source§

impl Authorization

Source

pub fn jar(&self, secure: bool) -> CookieJar

Builds the per-request cookie jar.

Source§

impl Authorization

Stores a signed, short-lived intent marker for the OAuth round-trip.

Source

pub fn consume_flow_intent( &self, w: &mut ResponseWriter, r: &RequestContext<'_>, jar: &CookieJar, intent: &str, ) -> bool

Reads and clears the intent cookie, reporting whether it carried the expected, correctly signed intent.

Source§

impl Authorization

Source

pub fn parse_jwt(&self, raw: &str) -> Result<JwtToken>

Validates a raw token against the configured secret and returns it.

Source

pub fn use_api_authorization( &self, opts: impl IntoIterator<Item = AuthConfigOptions>, ) -> ApiAuthorizationLayer

Returns a layer that protects API routes with a Bearer JWT.

On success the validated token is stored on the request extensions (see Authorization::get_claims and crate::claims::jwt_from_context); optional roles are enforced.

Source

pub fn use_web_authorization( &self, opts: impl IntoIterator<Item = AuthConfigOptions>, ) -> WebAuthorizationLayer

Returns a layer that protects WEB routes with a session cookie.

Missing or invalid cookies are redirected to the sign-in URL, preserving the original request URL in redirectUrl.

Source

pub fn get_auth_redirect_url(&self, r: &RequestContext<'_>) -> String

Builds the sign-in URL with a redirectUrl query parameter pointing back at the original request, preserving the browser scheme.

Source§

impl Authorization

Source

pub fn with_excluded_paths( &self, paths: impl IntoIterator<Item = impl Into<String>>, ) -> AuthConfigOptions

Whitelists path prefixes that should not require auth.

Source

pub fn with_roles( &self, roles: impl IntoIterator<Item = impl Into<String>>, ) -> AuthConfigOptions

Gates the route behind the given role names; the authenticated user must hold at least one of them.

Source§

impl Authorization

Source

pub fn find_provider(&self, id: &str) -> Option<&Arc<dyn Provider>>

Returns the configured provider with the given id.

Source§

impl Authorization

Source

pub fn origin(&self, r: &RequestContext<'_>) -> Result<(String, bool)>

Resolves the external base URL and whether it is HTTPS, honouring Config::auth_url and falling back to request headers when it is unset.

Source

pub fn callback_url(&self, origin: &str, provider_id: &str) -> String

Builds the provider callback URL for the current request.

Source

pub fn sign_in_url(&self, origin: &str, provider_id: &str) -> String

Builds the provider sign-in URL for the current request.

Source§

impl Authorization

Source

pub fn callback_target(&self, r: &RequestContext<'_>, origin: &str) -> String

Extracts the requested post-action redirect target from the form, query or cookie, defaulting to the origin.

Source§

impl Authorization

Source

pub fn handle_refresh_token(&self) -> RefreshTokenLayer

Returns a layer that conditionally handles refresh-token requests.

The request is only handled when the client opts in by setting the REFRESH_TOKEN_HANDLER_IDENTIFIER header; every other request is forwarded to the inner service.

On success the response body is the new access token; on failure a JSON envelope with an error message and machine-readable code is returned.

Source§

impl Authorization

Source

pub fn redirect_or_json(&self, r: &RequestContext<'_>, target: &str) -> Response

Either issues an HTTP redirect or returns the target URL as JSON, matching the Auth.js client convention (X-Auth-Return-Redirect).

Source§

impl Authorization

Source

pub fn get_roles(&self, r: &RequestContext<'_>) -> Result<Vec<String>>

Extracts the roles claim as a list of grants. Several encodings are accepted because the claim crosses JSON, JWT and database boundaries.

Source

pub fn get_role( &self, endpoint_roles: &[String], user_roles: &[String], ) -> (bool, bool, bool)

Checks authorization against endpoint role names and user role grants.

endpoint_roles are plain names required by the route (e.g. admin, hr). user_roles use name:perms where perms is r (read), w (write), or rw (both).

Returns (has_role, can_read, can_write):

  • has_role: the user has at least one endpoint role (the name before : matched)
  • can_read: a matched grant includes r or rw
  • can_write: a matched grant includes w or rw
Source§

impl Authorization

Source

pub async fn get_session(&self, session_id: &str) -> Result<Session>

Loads a session (and its user) by id, using the Redis cache when available.

Source

pub async fn get_session_from_db(&self, session_id: &str) -> Result<Session>

Loads a session from Redis when configured, falling back to the database.

Source

pub async fn get_session_from_redis( &self, session_id: &str, ) -> Result<SessionData>

Retrieves session data from the Redis cache.

Source

pub async fn set_session_to_redis(&self, session: &SessionData) -> Result<()>

Stores session data in the Redis cache.

Source

pub async fn create_session(&self, o: &AuthorizeOptions) -> Result<String>

Persists a new session row and returns its id.

Source

pub fn get_session_id(&self, r: &RequestContext<'_>) -> String

Returns the session id carried by the request’s session cookie, or "".

Writes the WEB session cookie used by Authorization::use_web_authorization.

Source§

impl Authorization

Source

pub async fn check_session( &self, w: &mut ResponseWriter, r: &RequestContext<'_>, ) -> Result<CheckSessionResult>

Validates an existing refresh token and session, refreshes the access token with up-to-date roles, and sets the WEB session cookie.

Source

pub async fn ensure_session_active(&self, session_id: &str) -> Result<()>

Loads the session row and checks that it may still authenticate requests.

Source§

impl Authorization

Source

pub fn get_token_from_header(&self, auth_header: &str) -> Result<String>

Strips the Bearer / Token scheme from an Authorization header value. Returns the value as-is when no scheme is set, and an error when the header is empty.

Source

pub fn extract_token(&self, token_string: &str) -> Result<RefreshTokenClaims>

Parses and validates a refresh token, returning its claims.

Source

pub fn refresh_access_token( &self, refresh_token_claims: &RefreshTokenClaims, session_data: &Session, opts: impl IntoIterator<Item = AuthorizeOptionsFunc>, ) -> Result<String>

Issues a new access token from a previously-validated refresh-token claim set and the matching session row.

Extra functional options can be passed to override the embedded content.

Source

pub fn sign_token_pair( &self, o: &AuthorizeOptions, session_id: &str, ) -> Result<(String, String)>

Signs an access and a refresh token in one shot. The current time is read once and reused so the lifetimes line up exactly.

Source

pub fn wants_tokens(&self, r: &RequestContext<'_>) -> bool

Reports whether the response should be tokens (JSON) rather than a session cookie plus redirect.

Source

pub fn check_csrf(&self, r: &RequestContext<'_>, secure: bool) -> bool

Validates the signed double-submit token for unsafe actions.

Source§

impl Authorization

Source

pub async fn get_user_roles_from_db(&self, user_id: &str) -> Result<JsonbArray>

Loads the current role grants of a user straight from the database.

Source

pub async fn user( &self, r: &RequestContext<'_>, from_api: bool, ) -> Result<AuthData>

Returns the authenticated principal for the current request.

Pass from_api = true to read it out of the JWT instead of the session cookie.

Source

pub fn get_auth_data_api(&self, r: &RequestContext<'_>) -> Result<AuthData>

Extracts the authenticated principal from a JWT-protected request.

Source

pub async fn get_auth_data_web( &self, r: &RequestContext<'_>, ) -> Result<AuthData>

Extracts the authenticated principal from a cookie-protected request by loading the matching session row.

Source§

impl Authorization

Source

pub fn handler(&self) -> Router

Available on crate feature axum only.

Returns a router serving every endpoint under DEFAULT_BASE_PATH:

GET  {base}/providers                    -> get_providers
ANY  {base}/provider/{provider}          -> handle_sign_in
ANY  {base}/provider/{provider}/callback -> handle_callback

The three handlers are also callable individually if you prefer to register the routes yourself.

Trait Implementations§

Source§

impl Clone for Authorization

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Authorization

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more