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
impl Authorization
Sourcepub async fn route<B>(&self, req: Request<B>) -> Response
pub async fn route<B>(&self, req: Request<B>) -> Response
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}/providersANY {base}/provider/{provider}ANY {base}/provider/{provider}/callback
Sourcepub async fn get_providers<B>(&self, req: Request<B>) -> Response
pub async fn get_providers<B>(&self, req: Request<B>) -> Response
Lists the configured providers in the Auth.js-compatible shape.
Sourcepub async fn handle_sign_in<B>(&self, req: Request<B>) -> Response
pub async fn handle_sign_in<B>(&self, req: Request<B>) -> Response
Starts the sign-in flow for the provider named in the path: an OAuth redirect, or a credentials POST.
Sourcepub async fn handle_callback<B>(&self, req: Request<B>) -> Response
pub async fn handle_callback<B>(&self, req: Request<B>) -> Response
Handles the provider redirect back to this application.
Sourcepub fn with_user_id(&self, user_id: &str) -> AuthorizeOptionsFunc
pub fn with_user_id(&self, user_id: &str) -> AuthorizeOptionsFunc
Sets the user the session and tokens belong to.
Sourcepub fn with_user_roles(&self, roles: JsonbArray) -> AuthorizeOptionsFunc
pub fn with_user_roles(&self, roles: JsonbArray) -> AuthorizeOptionsFunc
Sets the role grants embedded in the tokens.
Sourcepub fn with_content(&self, content: JsonbAny) -> AuthorizeOptionsFunc
pub fn with_content(&self, content: JsonbAny) -> AuthorizeOptionsFunc
Sets the arbitrary content embedded in the access/refresh token claims.
Sourcepub fn with_account(&self, account: Account) -> AuthorizeOptionsFunc
pub fn with_account(&self, account: Account) -> AuthorizeOptionsFunc
Attaches the provider account stored on the session row.
Sourcepub fn with_ip_address(&self, ip_address: &str) -> AuthorizeOptionsFunc
pub fn with_ip_address(&self, ip_address: &str) -> AuthorizeOptionsFunc
Records the caller’s IP address on the session row.
Sourcepub fn with_user_agent(&self, user_agent: &str) -> AuthorizeOptionsFunc
pub fn with_user_agent(&self, user_agent: &str) -> AuthorizeOptionsFunc
Records the caller’s user agent on the session row.
Sourcepub fn with_method(&self, method: &str) -> AuthorizeOptionsFunc
pub fn with_method(&self, method: &str) -> AuthorizeOptionsFunc
Records how the session was established (the provider id).
Sourcepub fn session_meta_from_request(
&self,
r: &RequestContext<'_>,
method: &str,
) -> Vec<AuthorizeOptionsFunc> ⓘ
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
impl Authorization
Sourcepub fn new(config: Config) -> Result<Self>
pub fn new(config: Config) -> Result<Self>
Validates the configuration and returns a ready-to-use handle.
Sourcepub fn new_with(
config: Config,
opts: impl IntoIterator<Item = ConfigFunc>,
) -> Result<Self>
pub fn new_with( config: Config, opts: impl IntoIterator<Item = ConfigFunc>, ) -> Result<Self>
Applies the given options on top of config before validating it.
Sourcepub fn jwt_secret(&self) -> &str
pub fn jwt_secret(&self) -> &str
The HMAC signing secret.
Sourcepub fn signing_method(&self) -> &str
pub fn signing_method(&self) -> &str
The configured JWT signing method name.
Sourcepub fn access_token_duration(&self) -> &str
pub fn access_token_duration(&self) -> &str
The configured access-token lifetime.
Sourcepub fn refresh_token_duration(&self) -> &str
pub fn refresh_token_duration(&self) -> &str
The configured refresh-token lifetime.
Sourcepub fn sign_in_redirect_url(&self) -> &str
pub fn sign_in_redirect_url(&self) -> &str
The configured sign-in redirect target.
Sourcepub fn db(&self) -> Result<&PgPool>
pub fn db(&self) -> Result<&PgPool>
The database pool, or Error::NotInitialized when none was configured.
Sourcepub fn redis_prefix(&self) -> &str
pub fn redis_prefix(&self) -> &str
The Redis key prefix.
Sourcepub fn user_table_name(&self) -> &str
pub fn user_table_name(&self) -> &str
The configured users table.
Sourcepub fn sessions_table(&self) -> &str
pub fn sessions_table(&self) -> &str
The configured sessions table.
The name of the WEB session cookie.
The configured cookie overrides.
Sourcepub fn with_jwt_secret(self, jwt_secret: &str) -> Self
pub fn with_jwt_secret(self, jwt_secret: &str) -> Self
Overrides the signing secret.
Sourcepub fn with_auth_url(self, auth_url: &str) -> Self
pub fn with_auth_url(self, auth_url: &str) -> Self
Overrides the external origin.
Sourcepub fn with_redis(self, redis: Client) -> Self
pub fn with_redis(self, redis: Client) -> Self
Overrides the Redis client.
Sourcepub fn with_redis_prefix(self, redis_prefix: &str) -> Self
pub fn with_redis_prefix(self, redis_prefix: &str) -> Self
Overrides the Redis key prefix.
Sourcepub fn with_redis_ttl(self, redis_ttl: Duration) -> Self
pub fn with_redis_ttl(self, redis_ttl: Duration) -> Self
Overrides the Redis session time-to-live.
Overrides the WEB session cookie name.
Sourcepub fn with_resolve_user(self, resolve_user: ResolveUserFn) -> Self
pub fn with_resolve_user(self, resolve_user: ResolveUserFn) -> Self
Overrides the user-resolution callback.
Source§impl Authorization
impl Authorization
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
impl Authorization
Sourcepub fn render_callback_page<T: Serialize>(&self, data: T) -> Response
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
impl Authorization
Sourcepub fn get_claims<'a>(
&self,
r: &'a RequestContext<'a>,
) -> Result<&'a JsonMap<String, Value>>
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
impl Authorization
Stores the target resource id for a provider-connect OAuth round-trip.
Reads and clears the connect-resource cookie.
Source§impl Authorization
impl Authorization
Source§impl Authorization
impl Authorization
Stores a signed, short-lived intent marker for the OAuth round-trip.
Sourcepub fn consume_flow_intent(
&self,
w: &mut ResponseWriter,
r: &RequestContext<'_>,
jar: &CookieJar,
intent: &str,
) -> bool
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
impl Authorization
Sourcepub fn parse_jwt(&self, raw: &str) -> Result<JwtToken>
pub fn parse_jwt(&self, raw: &str) -> Result<JwtToken>
Validates a raw token against the configured secret and returns it.
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.
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.
Sourcepub fn get_auth_redirect_url(&self, r: &RequestContext<'_>) -> String
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
impl Authorization
Sourcepub fn with_excluded_paths(
&self,
paths: impl IntoIterator<Item = impl Into<String>>,
) -> AuthConfigOptions
pub fn with_excluded_paths( &self, paths: impl IntoIterator<Item = impl Into<String>>, ) -> AuthConfigOptions
Whitelists path prefixes that should not require auth.
Sourcepub fn with_roles(
&self,
roles: impl IntoIterator<Item = impl Into<String>>,
) -> AuthConfigOptions
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
impl Authorization
Source§impl Authorization
impl Authorization
Sourcepub fn origin(&self, r: &RequestContext<'_>) -> Result<(String, bool)>
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.
Sourcepub fn callback_url(&self, origin: &str, provider_id: &str) -> String
pub fn callback_url(&self, origin: &str, provider_id: &str) -> String
Builds the provider callback URL for the current request.
Sourcepub fn sign_in_url(&self, origin: &str, provider_id: &str) -> String
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
impl Authorization
Sourcepub fn callback_target(&self, r: &RequestContext<'_>, origin: &str) -> String
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
impl Authorization
Sourcepub fn handle_refresh_token(&self) -> RefreshTokenLayer
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
impl Authorization
Sourcepub fn redirect_or_json(&self, r: &RequestContext<'_>, target: &str) -> Response
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
impl Authorization
Sourcepub fn get_roles(&self, r: &RequestContext<'_>) -> Result<Vec<String>>
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.
Sourcepub fn get_role(
&self,
endpoint_roles: &[String],
user_roles: &[String],
) -> (bool, bool, bool)
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 includesrorrwcan_write: a matched grant includesworrw
Source§impl Authorization
impl Authorization
Sourcepub async fn get_session(&self, session_id: &str) -> Result<Session>
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.
Sourcepub async fn get_session_from_db(&self, session_id: &str) -> Result<Session>
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.
Sourcepub async fn get_session_from_redis(
&self,
session_id: &str,
) -> Result<SessionData>
pub async fn get_session_from_redis( &self, session_id: &str, ) -> Result<SessionData>
Retrieves session data from the Redis cache.
Sourcepub async fn set_session_to_redis(&self, session: &SessionData) -> Result<()>
pub async fn set_session_to_redis(&self, session: &SessionData) -> Result<()>
Stores session data in the Redis cache.
Sourcepub async fn create_session(&self, o: &AuthorizeOptions) -> Result<String>
pub async fn create_session(&self, o: &AuthorizeOptions) -> Result<String>
Persists a new session row and returns its id.
Sourcepub fn get_session_id(&self, r: &RequestContext<'_>) -> String
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
impl Authorization
Sourcepub async fn check_session(
&self,
w: &mut ResponseWriter,
r: &RequestContext<'_>,
) -> Result<CheckSessionResult>
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.
Sourcepub async fn ensure_session_active(&self, session_id: &str) -> Result<()>
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
impl Authorization
Sourcepub fn get_token_from_header(&self, auth_header: &str) -> Result<String>
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.
Sourcepub fn extract_token(&self, token_string: &str) -> Result<RefreshTokenClaims>
pub fn extract_token(&self, token_string: &str) -> Result<RefreshTokenClaims>
Parses and validates a refresh token, returning its claims.
Sourcepub fn refresh_access_token(
&self,
refresh_token_claims: &RefreshTokenClaims,
session_data: &Session,
opts: impl IntoIterator<Item = AuthorizeOptionsFunc>,
) -> Result<String>
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.
Sourcepub fn sign_token_pair(
&self,
o: &AuthorizeOptions,
session_id: &str,
) -> Result<(String, String)>
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.
Sourcepub fn wants_tokens(&self, r: &RequestContext<'_>) -> bool
pub fn wants_tokens(&self, r: &RequestContext<'_>) -> bool
Reports whether the response should be tokens (JSON) rather than a session cookie plus redirect.
Sourcepub fn check_csrf(&self, r: &RequestContext<'_>, secure: bool) -> bool
pub fn check_csrf(&self, r: &RequestContext<'_>, secure: bool) -> bool
Validates the signed double-submit token for unsafe actions.
Source§impl Authorization
impl Authorization
Sourcepub async fn get_user_roles_from_db(&self, user_id: &str) -> Result<JsonbArray>
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.
Sourcepub async fn user(
&self,
r: &RequestContext<'_>,
from_api: bool,
) -> Result<AuthData>
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.
Sourcepub fn get_auth_data_api(&self, r: &RequestContext<'_>) -> Result<AuthData>
pub fn get_auth_data_api(&self, r: &RequestContext<'_>) -> Result<AuthData>
Extracts the authenticated principal from a JWT-protected request.
Sourcepub async fn get_auth_data_web(
&self,
r: &RequestContext<'_>,
) -> Result<AuthData>
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
impl Authorization
Sourcepub fn handler(&self) -> Router
Available on crate feature axum only.
pub fn handler(&self) -> Router
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_callbackThe three handlers are also callable individually if you prefer to register the routes yourself.
Trait Implementations§
Source§impl Clone for Authorization
impl Clone for Authorization
Auto Trait Implementations§
impl !RefUnwindSafe for Authorization
impl !UnwindSafe for Authorization
impl Freeze for Authorization
impl Send for Authorization
impl Sync for Authorization
impl Unpin for Authorization
impl UnsafeUnpin for Authorization
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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