Expand description
Framework-agnostic authentication and authorization for Rust.
Built on http and [tower]: OAuth 2.0 / OpenID Connect, credentials,
LDAP, JWT access/refresh tokens, PostgreSQL sessions (optional Redis cache),
cookies, CSRF protection, and role-based access control.
§Getting started
- Add the crate (the
axumfeature is on by default):
[dependencies]
authrust = "0.1"- Build an
Authorizationfrom aConfig, then mount the handlers and layers on your router:
use std::sync::Arc;
use authrust::{Authorization, Config, providers::google};
let pool = sqlx::PgPool::connect("postgres://localhost/app").await?;
let auth = Authorization::new(Config {
db: Some(pool),
jwt_secret: "a-long-random-secret".into(),
providers: vec![google::new("client-id", "client-secret")],
resolve_user: Some(Arc::new(|profile| {
Box::pin(async move {
// Look the profile up in your own tables, creating it if needed,
// and return the user plus whether it was just created.
let _ = profile;
Ok((Some(authrust::User::default()), false))
})
})),
..Config::default()
})?;
let app = axum::Router::new()
.merge(auth.handler())
.layer(auth.use_api_authorization([]));§What you get
| Area | Details |
|---|---|
| Providers | Google, Azure AD / Entra ID, credentials, LDAP — see providers |
| Tokens | HS256 / HS384 / HS512 access + refresh pairs |
| Sessions | PostgreSQL via sqlx, optional Redis cache |
| API protection | Authorization::use_api_authorization — Bearer JWT |
| Web protection | Authorization::use_web_authorization — session cookie + redirect |
| Refresh | Authorization::handle_refresh_token — opt-in refresh endpoint |
| RBAC | name:perms grants (admin:rw, hr:r, …) |
§HTTP endpoints
With the axum feature, Authorization::handler mounts routes under
DEFAULT_BASE_PATH (/api/authorization):
GET {base}/providers— list configured providers{base}/provider/{provider}— start sign-in{base}/provider/{provider}/callback— OAuth/OIDC callback
Without axum, register the individual handlers yourself or use
Authorization::route as a catch-all dispatcher.
§Frameworks
Middlewares are tower layers and handlers are plain http services, so the
crate works with axum, hyper, tonic, and other tower stacks. actix-web needs
a thin adapter (see the repository examples).
§Crate features
| Feature | Default | Description |
|---|---|---|
axum | yes | Enables Authorization::handler returning an axum::Router |
§Re-exports
Common types are re-exported at the crate root so call sites stay short
(authrust::Authorization, authrust::Config, …).
Re-exports§
pub use authorization::Authorization;pub use authorization::Config;pub use authorization::ConfigFunc;pub use authorization::OnProviderConnectFn;pub use authorization::ResolveUserFn;pub use authorize::AuthorizeOptions;pub use authorize::AuthorizeOptionsFunc;pub use checks::pkce_challenge;pub use checks::provider_uses_check;pub use checks::random_string;pub use claims::JwtToken;pub use claims::jwt_from_context;pub use claims::with_jwt;pub use constants::DEFAULT_ACCESS_TOKEN_DURATION;pub use constants::DEFAULT_BASE_PATH;pub use constants::DEFAULT_COOKIE_SESSION_NAME;pub use constants::DEFAULT_REDIS_PREFIX;pub use constants::DEFAULT_REDIS_TTL;pub use constants::DEFAULT_REFRESH_TOKEN_DURATION;pub use constants::DEFAULT_SESSION_TABLE_NAME;pub use constants::DEFAULT_SIGN_IN_REDIRECT_URL;pub use constants::DEFAULT_SIGNING_METHOD_HMAC;pub use constants::DEFAULT_USER_TABLE_NAME;pub use constants::REAUTHORIZE_HANDLER_IDENTIFIER;pub use constants::REFRESH_TOKEN_HANDLER_IDENTIFIER;pub use cookies::CookieJar;pub use cookies::CookieOption;pub use cookies::CookieOptions;pub use csrf::csrf_hash;pub use csrf::verify_csrf;pub use errors::BoxError;pub use errors::Error;pub use errors::Result;pub use http::ClientAddr;pub use http::ConnectionSecure;pub use http::RequestContext;pub use http::client_ip;pub use middleware::ApiAuthorization;pub use middleware::ApiAuthorizationLayer;pub use middleware::WebAuthorization;pub use middleware::WebAuthorizationLayer;pub use options::AuthConfig;pub use options::AuthConfigOptions;pub use options::new_auth_config_options;pub use password::check_password;pub use password::hash_password;pub use provider::Check;pub use provider::CredentialField;pub use provider::CredentialsAuthorizeFn;pub use provider::CredentialsProvider;pub use provider::CredentialsRequest;pub use provider::OAuthProvider;pub use provider::ProfileFn;pub use provider::Provider;pub use provider::ProviderType;pub use provider::PublicProvider;pub use provider::UrlValues;pub use refresh::RefreshToken;pub use refresh::RefreshTokenLayer;pub use response::BoxedBody;pub use response::BoxedResponse;pub use response::Response;pub use response::ResponseWriter;pub use roles::format_roles;pub use roles::roles_from_any;pub use session::Session;pub use session::SessionData;pub use session::SessionType;pub use session_check::CheckSessionResult;pub use token::Claims;pub use token::RefreshTokenClaims;pub use token::Tokens;pub use types::Account;pub use types::JsonbAny;pub use types::JsonbArray;pub use types::Profile;pub use types::TokenSet;pub use user::AuthData;pub use user::OAuthUser;pub use user::User;pub use utils::build_redis_key;pub use utils::deserialize_session_data;pub use utils::format_user;pub use utils::is_excluded_path;pub use utils::parse_custom_duration;
Modules§
- action_
auth - Auth HTTP handlers: providers list, sign-in, and OAuth/OIDC callback.
- authorization
- Configuration and the
Authorizationhandle. - authorize
- Session creation and token issuance.
- callback_
page - The HTML page rendered at the end of an OAuth round-trip.
- checks
- OAuth security checks: random values, PKCE challenges and per-provider check selection.
- claims
- Access to the validated JWT that the API middleware attaches to a request.
- connect_
resource - The target resource id carried through a provider-connect OAuth round-trip.
- constants
- Token, session and cookie defaults, plus the header identifiers used by the middlewares to coordinate optional flows.
- cookies
- Cookie definitions and helpers.
- csrf
- CSRF protection.
- errors
- Error type for the crate.
- flow_
intent - Signed, short-lived markers that survive the OAuth round-trip.
- http
- Request plumbing shared by the handlers and middlewares.
- middleware
- Route protection as
tower_layer::Layers. - oauth
- The OAuth 2.0 / OpenID Connect wire protocol: authorization URLs, code exchange and userinfo lookups.
- options
- Per-route middleware configuration.
- password
- PBKDF2-SHA256 password hashing for credentials storage.
- provider
- The provider model: OAuth/OIDC services and credentials forms.
- provider_
utils - Origin resolution, callback parameter merging and OIDC discovery.
- providers
- Built-in identity provider presets.
- redirect
- Post-action redirect resolution.
- refresh
- The opt-in refresh-token endpoint middleware.
- response
- Response construction: JSON envelopes, redirects and the header buffer that
stands in for Go’s
http.ResponseWriter. - roles
- Role parsing and the
name:permsgrant model. - session
- Session rows, their Redis cache and the WEB session cookie.
- session_
check - Refresh-token driven session validation.
- token
- JWT claims, header parsing and token issuance.
- types
- Provider payload types and the JSONB helpers used for database columns.
- user
- User records and the authenticated principal of a request.
- utils
- Shared helpers: path matching, Redis key/value plumbing, signing-method resolution and the package’s custom duration format.