Skip to main content

AuthLayer

Struct AuthLayer 

Source
pub struct AuthLayer { /* private fields */ }
Available on crate feature axum only.
Expand description

Which credentials are accepted, where they are read from, and how a refusal looks. Cheap to clone (one Arc).

It is a tower::Layer, so router.route_layer(auth) (or .layer(auth)) protects routes directly; it is also the state for the require_auth middleware function (axum::middleware::from_fn_with_state(auth, require_auth)), which behaves identically.

Fail-closed by construction. AuthLayer::builder refuses to build without at least one credential; the only way to get a layer that lets requests through unauthenticated is to call AuthLayer::allow_unauthenticated by name (or to hand AuthLayer::from_decision or AuthLayerBuilder::build_with_decision a StaticTokenDecision::Unauthenticated, which crate::static_token_policy returns only when its allow_unauthenticated argument is true, and which can otherwise only be named directly).

Built once at startup. Nothing in it hot-reloads: a changed static token or OAuth config takes effect when a new layer is built, which in practice means a restart.

Implementations§

Source§

impl AuthLayer

Source

pub fn builder() -> AuthLayerBuilder

Start building an enforcing layer.

Give it a static token, an OAuth validator, or both; optionally the credential sources (default: Authorization: Bearer) and an on_reject callback. To honour accept_static_bearer, finish with build_with_decision and a crate::static_token_policy decision rather than setting the static token directly.

§Examples
use axum::{Router, http::HeaderName, routing::get};
use oauth_resource_server::axum::{AuthLayer, AuthLayerError, CredentialSource};

// A static API key accepted from either header. (With OAuth, add
// `.oauth(validator)` as well.)
let auth = AuthLayer::builder()
    .static_token("example-static-key")
    .sources([
        CredentialSource::authorization_bearer(),
        CredentialSource::Raw(HeaderName::from_static("x-api-key")),
    ])
    .build()
    .unwrap();
let app: Router = Router::new()
    .route("/api", get(|| async { "protected" }))
    .route_layer(auth);

// Fail closed: no credential configured is an error, not a pass-through.
assert_eq!(AuthLayer::builder().build().unwrap_err(), AuthLayerError::NoCredential);
Source

pub fn allow_unauthenticated() -> Self

A layer that lets EVERY request through, unauthenticated, and inserts no credential into request extensions (so Option<Credential> and Option<AuthorizedToken> extract None, and the non-Option extractors refuse with a 401 carrying DEFAULT_STATIC_CHALLENGE; see the module docs).

The explicit opt-out. The only other pass-through is a crate::StaticTokenDecision::Unauthenticated handed to AuthLayer::from_decision or AuthLayerBuilder::build_with_decision, which builds this same layer. Pair it with a loud startup warning. crate::static_token_policy returns crate::StaticTokenDecision::Unauthenticated exactly when an application has chosen this.

§Security

Every request reaches the protected routes. Use it only where something else (a trusted network, a proxy that authenticates) stands in front. It still marks every Authorization header value sensitive (http::HeaderValue::set_sensitive), so a credential a client sends anyway is not printed by a Debug of the request downstream.

Source

pub fn from_decision( decision: StaticTokenDecision, oauth: Option<Arc<OAuthValidator>>, ) -> Result<Self, AuthLayerError>

The layer a crate::static_token_policy decision calls for, with the default source (Authorization: Bearer) and refusal shape — the whole startup mapping in one call. Shorthand for AuthLayer::builder().optional_oauth(oauth).build_with_decision(decision); use that form to set sources or on_reject as well.

§Errors

See AuthLayerBuilder::build_with_decision.

Source

pub fn allows_unauthenticated(&self) -> bool

Whether this is the AuthLayer::allow_unauthenticated pass-through.

Source

pub fn oauth(&self) -> Option<&Arc<OAuthValidator>>

The OAuth validator, when one is configured.

Trait Implementations§

Source§

impl Clone for AuthLayer

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 AuthLayer

Hand-written so the static token never reaches a log line through {:?}.

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<S> Layer<S> for AuthLayer

Source§

type Service = AuthService<S>

The wrapped service
Source§

fn layer(&self, inner: S) -> Self::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.

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<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> 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> 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<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