auth only.Expand description
Built-in authentication middleware (auth Cargo feature).
Enable with features = ["auth"] in your Cargo.toml. Adds hmac and
sha2 (RustCrypto) as dependencies.
§HTTP Basic Auth
BasicAuthLayer validates Authorization: Basic <base64> credentials
against a caller-supplied closure. Issues a WWW-Authenticate challenge
when the header is absent.
§JWT (HS256)
JwtLayer verifies Authorization: Bearer <token> JWTs signed with
HMAC-SHA256. Tokens with a past exp claim are rejected. Use
verify_jwt directly in a handler if you also need the decoded
Claims.
§JWT (RS256 / ES256), auth-asymmetric feature
JwtLayer::rs256 and JwtLayer::es256 verify JWTs signed with a
separate auth server’s RSA or P-256 private key — the caller presents a
token, JwtLayer only needs the corresponding public key (PEM,
SubjectPublicKeyInfo format) to verify it. No JWKS endpoint or the full
sso feature is required; use crate::sso::JwksCache instead if you
need multi-key rotation via a live JWKS URL.
§Example
use rust_web_server::app::App;
use rust_web_server::auth::{BasicAuthLayer, JwtLayer};
use rust_web_server::core::New;
// Basic Auth
let app = App::new()
.wrap(BasicAuthLayer::new(|user, pass| user == "admin" && pass == "secret"));
// JWT (HS256)
let app = App::new()
.wrap(JwtLayer::new(b"my-signing-secret"));use rust_web_server::app::App;
use rust_web_server::auth::JwtLayer;
use rust_web_server::core::New;
// JWT (RS256) — public_key_pem is a SubjectPublicKeyInfo PEM string,
// e.g. produced by `openssl rsa -in key.pem -pubout`.
let public_key_pem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n";
let app = App::new().wrap(JwtLayer::rs256(public_key_pem).unwrap());Modules§
- forward
- Forward-auth middleware — delegates the allow/deny decision for every
request to an external HTTP service (Traefik’s
forwardAuth, nginx’sauth_request), so a policy engine (OPA, Casbin) or a centralized auth service can gate requests without embedding that logic in rws.
Structs§
- Basic
Auth Layer - Middleware that validates HTTP Basic Auth credentials.
- Claims
- Decoded JWT payload.
- JwtLayer
- Middleware that verifies
Authorization: Bearer <token>JWTs.
Functions§
- build_
jwt - Build a signed HS256 JWT from a JSON claims object.
- extract_
bearer_ token - Extract the raw token string from
Authorization: Bearer <token>. ReturnsNoneif the header is absent or does not start withBearer. - verify_
jwt - Verify a JWT string against
secret(HS256 only). - verify_
jwt_ es256 auth-asymmetric - Verify a JWT signed with ES256 (ECDSA using P-256 and SHA-256) against a P-256 public key.
- verify_
jwt_ rs256 auth-asymmetric - Verify a JWT signed with RS256 (RSASSA-PKCS1-v1_5 using SHA-256) against an RSA public key.