Expand description
Security schemes as self-documenting extractors: HTTP Bearer, HTTP Basic, API keys and the OAuth2 password flow.
Every scheme is a FromRequestParts extractor. Besides reading the
credentials, it documents itself: it registers an entry under
components.securitySchemes and adds a security requirement to the
operation, so the OpenAPI document mirrors the handler signature.
Missing or malformed credentials yield 401 Unauthorized with a
WWW-Authenticate challenge (Bearer, or Basic realm="api"). API keys
have no standard challenge, so they answer 401 without one.
§Verifying credentials
The extractors only read credentials; they never decide whether they
are valid. Implement Authenticate to turn credentials into a
principal and use Security to run it. When comparing secrets (API
keys, passwords, tokens) use a constant-time comparison such as the
subtle crate: == on strings leaks timing information. That is the
application’s responsibility, not this module’s.
use siderite_core::security::{Authenticate, HttpBearer, Security, check_scopes};
use siderite_core::{ApiError, scopes};
use http::StatusCode;
use http::request::Parts;
struct CurrentUser(String);
impl Authenticate for CurrentUser {
type Credentials = HttpBearer;
async fn authenticate(
credentials: HttpBearer,
required: &[&'static str],
_parts: &Parts,
) -> Result<Self, ApiError> {
// Look the token up in your own store here.
let granted = ["read"];
check_scopes(required, granted)?;
Ok(CurrentUser(credentials.token))
}
}
scopes!(ReadScopes = ["read"]);
async fn me(Security(user, _): Security<CurrentUser, ReadScopes>) -> String {
user.0
}Password-flow types are legacy compatibility. New OAuth applications use authorization code with PKCE; extraction does not validate access tokens.
Structs§
- ApiKey
- An API key described by
S. - Http
Basic - Credentials from
Authorization: Basic <base64(user:pass)>(schemeHTTPBasic). - Http
Bearer - Bearer token from
Authorization: Bearer <token>(schemeHTTPBearer). - NoScopes
- No required scopes (the default for
Security). - OAuth2
Password Bearer - Bearer token for an OAuth2 password flow described by
S. - OAuth2
Password Request Form - The token-endpoint form of the OAuth2 password flow
(
application/x-www-form-urlencoded, RFC 6749 section 4.3.2). - Security
Security<CurrentUser, AdminScopes>: extracts credentials, runsAuthenticate::authenticate(403on missing scopes), and documents the scheme together with the required scopes.
Enums§
- ApiKey
Location - Where an API key is carried.
Traits§
- ApiKey
Spec - Describes one API-key scheme; implement on a marker type.
- Authenticate
- User-defined principal built from a scheme’s credentials.
- OAuth2
Spec - Describes one OAuth2 password-flow scheme; implement on a marker type.
- Scopes
- Required scopes, as a marker type (const
&strgenerics are unstable).
Functions§
- check_
scopes - Build the
403 Forbiddenerror for a principal lacking scopes.