Skip to main content

TokenBuilder

Struct TokenBuilder 

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

A fluent builder for a signed JWT access token, from TestAuthority::token. Every method changes one thing about the token, so a test states exactly what is wrong (or different) about it; the defaults are documented on TestAuthority::token.

Time setters are relative to now and in seconds (expires_in, expired, not_before_in, issued_ago). For an absolute or odd value use claim: .claim("nbf", 4102444800_u64), .claim("exp", "soon").

Claim-shaping calls apply in this order: the fields above (iss, aud, sub, scope, exp, iat, nbf), then claim overrides, then without_claim removals, so without_claim("exp") really produces a token with no exp.

§Examples

use oauth_resource_server::Algorithm;
use oauth_resource_server::testing::TestAuthority;

let authority = TestAuthority::start().await;
let jwt = authority
    .token()
    .subject("ada")
    .scopes(["api:read", "api:write"])
    .audience("https://other.example.test/")
    .expires_in(60)
    .typ("at+jwt")
    .alg(Algorithm::ES256)
    .claim("groups", ["admins"])
    .sign();
assert_eq!(jwt.split('.').count(), 3);

Implementations§

Source§

impl TokenBuilder

Source

pub fn subject(self, subject: impl Into<String>) -> Self

Set sub.

Source

pub fn scopes<I, S>(self, scopes: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

Replace the scopes, carried in the space-delimited scope claim. An empty list omits the claim.

Source

pub fn audience(self, audience: impl Into<String>) -> Self

Set aud to this one audience (a JSON string).

Source

pub fn audiences<I, S>(self, audiences: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

Set aud to these audiences (a JSON array, or a string when there is exactly one).

Source

pub fn issuer(self, issuer: impl Into<String>) -> Self

Override iss (default: the authority’s issuer), for a wrong-issuer test.

Source

pub fn expires_in(self, secs: u64) -> Self

Make the token expire secs seconds from now.

Source

pub fn expired(self) -> Self

Make the token expired: exp an hour in the past, well beyond the default 60-second leeway.

Source

pub fn not_before_in(self, secs: u64) -> Self

Set nbf to secs seconds in the future, so the token is not yet valid (mind the default 60-second leeway).

Source

pub fn issued_ago(self, secs: u64) -> Self

Set iat to secs seconds in the past (default: now).

Source

pub fn typ(self, typ: impl Into<String>) -> Self

Set the JOSE header typ (default at+jwt, RFC 9068).

Source

pub fn without_typ(self) -> Self

Omit the JOSE header typ entirely.

Source

pub fn alg(self, alg: Algorithm) -> Self

Sign with alg (default Algorithm::RS256), using the matching throwaway key: the active RSA key for RS*/PS*, the P-256 key for ES256, the Ed25519 key for EdDSA. All of them are published by the authority, each under its own kid. The header kid follows unless kid overrides it. ES384 has no throwaway key: sign panics for it.

Source

pub fn kid(self, kid: impl Into<String>) -> Self

Set the header kid, overriding the one that names the signing key (for an unknown-kid or “signed by one key, labelled as another” test).

Source

pub fn claim(self, name: impl Into<String>, value: impl Serialize) -> Self

Set (or override) one claim, any JSON-serializable value. This is also how to set an absolute or malformed exp/nbf/iat.

§Panics

If value fails to serialize.

Source

pub fn without_claim(self, name: impl Into<String>) -> Self

Leave a claim out of the token, including a default one such as exp, aud or iss.

Source

pub fn sign(self) -> String

Sign the token and return the compact JWT.

§Panics

If alg is an algorithm with no throwaway key (ES384).

Trait Implementations§

Source§

impl Clone for TokenBuilder

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 TokenBuilder

Source§

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

Formats the value using the given formatter. Read more

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