Struct openid::Client

source ·
pub struct Client<P = Discovered, C: CompactJson + Claims = StandardClaims> {
    pub provider: P,
    pub client_id: String,
    pub client_secret: Option<String>,
    pub redirect_uri: Option<String>,
    pub http_client: Client,
    pub jwks: Option<JWKSet<Empty>>,
    /* private fields */
}
Expand description

OpenID Connect 1.0 / OAuth 2.0 client.

Fields§

§provider: P

OAuth provider.

§client_id: String

Client ID.

§client_secret: Option<String>

Client secret.

§redirect_uri: Option<String>

Redirect URI.

§http_client: Client§jwks: Option<JWKSet<Empty>>

Implementations§

source§

impl<C: CompactJson + Claims> Client<Discovered, C>

source

pub async fn discover( id: String, secret: impl Into<Option<String>>, redirect: impl Into<Option<String>>, issuer: Url ) -> Result<Self, Error>

Constructs a client from an issuer url and client parameters via discovery

source

pub async fn discover_with_client( http_client: Client, id: String, secret: impl Into<Option<String>>, redirect: impl Into<Option<String>>, issuer: Url ) -> Result<Self, Error>

Constructs a client from an issuer url and client parameters via discovery

source§

impl<C: CompactJson + Claims, P: Provider + Configurable> Client<P, C>

source

pub fn redirect_url(&self) -> &str

Passthrough to the redirect_url stored in inth_oauth2 as a str.

source

pub fn config(&self) -> &Config

A reference to the config document of the provider obtained via discovery

source

pub fn auth_url(&self, options: &Options) -> Url

Constructs the auth_url to redirect a client to the provider. Options are… optional. Use them as needed. Keep the Options struct around for authentication, or at least the nonce and max_age parameter - we need to verify they stay the same and validate if you used them.

source

pub async fn authenticate( &self, auth_code: &str, nonce: impl Into<Option<&str>>, max_age: impl Into<Option<&Duration>> ) -> Result<Token<C>, Error>

Given an auth_code and auth options, request the token, decode, and validate it.

source

pub fn decode_token<T: CompactJson>( &self, token: &mut IdToken<T> ) -> Result<(), Error>

Mutates a Compact::encoded Token to Compact::decoded.

§Errors
source

pub fn validate_token<'nonce, 'max_age>( &self, token: &IdToken<C>, nonce: impl Into<Option<&'nonce str>>, max_age: impl Into<Option<&'max_age Duration>> ) -> Result<(), Error>

Validate a decoded token. If you don’t get an error, its valid! Nonce and max_age come from your auth_uri options.

§Errors
source

pub async fn request_userinfo( &self, token: &Token<C> ) -> Result<Userinfo, Error>

Get a userinfo json document for a given token at the provider’s userinfo endpoint. Returns Standard Claims as Userinfo struct.

§Errors
source

pub async fn request_userinfo_custom<U>( &self, token: &Token<C> ) -> Result<U, Error>

Get a userinfo json document for a given token at the provider’s userinfo endpoint. Returns UserInfo Response including non-standard claims. The sub (subject) Claim MUST always be returned in the UserInfo Response.

§Errors
§Examples
#[derive(Debug, Deserialize, Serialize)]
struct CustomUserinfo(std::collections::HashMap<String, serde_json::Value>);

impl StandardClaimsSubject for CustomUserinfo {
   fn sub(&self) -> Result<&str, StandardClaimsSubjectMissing> {
       self.0
           .get("sub")
           .and_then(|x| x.as_str())
           .ok_or(StandardClaimsSubjectMissing)
   }
}

impl openid::CompactJson for CustomUserinfo {}

let custom_userinfo: CustomUserinfo = client.request_userinfo_custom(&token).await?;
source§

impl<P, C> Client<P, C>
where P: Provider, C: CompactJson + Claims,

source

pub fn new( provider: P, client_id: String, client_secret: impl Into<Option<String>>, redirect_uri: impl Into<Option<String>>, http_client: Client, jwks: Option<JWKSet<Empty>> ) -> Self

Creates a client.

§Examples
use openid::{Client, StandardClaims};
use openid::provider::google::Installed;

let client: Client<_, StandardClaims> = Client::new(
    Installed,
    String::from("CLIENT_ID"),
    String::from("CLIENT_SECRET"),
    Some(String::from("urn:ietf:wg:oauth:2.0:oob")),
    reqwest::Client::new(), None,
);
source

pub fn auth_uri<'scope, 'state>( &self, scope: impl Into<Option<&'scope str>>, state: impl Into<Option<&'state str>> ) -> Url

Returns an authorization endpoint URI to direct the user to.

This function is used by Client::auth_url. In most situations it is non needed to use it directly.

See RFC 6749, section 3.1.

§Examples
use openid::Client;
use openid::provider::google::Installed;

let client: Client<_> = Client::new(
    Installed,
    String::from("CLIENT_ID"),
    String::from("CLIENT_SECRET"),
    Some(String::from("urn:ietf:wg:oauth:2.0:oob")),
    reqwest::Client::new(), None,
);

let auth_uri = client.auth_uri(
    Some("https://www.googleapis.com/auth/userinfo.email"),
    None,
);
source

pub async fn request_token(&self, code: &str) -> Result<Bearer, ClientError>

Requests an access token using an authorization code.

See RFC 6749, section 4.1.3.

source

pub async fn request_token_using_password_credentials( &self, username: &str, password: &str, scope: impl Into<Option<&str>> ) -> Result<Bearer, ClientError>

Requests an access token using the Resource Owner Password Credentials Grant flow

See RFC 6749, section 4.3

source

pub async fn request_token_using_client_credentials( &self, scope: impl Into<Option<&str>> ) -> Result<Bearer, ClientError>

Requests an access token using the Client Credentials Grant flow

See RFC 6749, section 4.4

source

pub async fn refresh_token( &self, token: impl AsRef<Bearer>, scope: impl Into<Option<&str>> ) -> Result<Bearer, ClientError>

Refreshes an access token.

See RFC 6749, section 6.

source

pub async fn ensure_token( &self, token_guard: TemporalBearerGuard ) -> Result<TemporalBearerGuard, ClientError>

Ensures an access token is valid by refreshing it if necessary.

source§

impl<C: CompactJson + Claims> Client<DiscoveredUma2, C>

source

pub async fn discover_uma2( id: String, secret: String, redirect: impl Into<Option<String>>, issuer: Url ) -> Result<Self, Error>

Constructs a client from an issuer url and client parameters via discovery

source§

impl<P, C> Client<P, C>

source

pub async fn associate_uma2_resource_with_a_permission( &self, token: String, resource_id: String, name: String, description: String, scopes: Vec<String>, roles: impl Into<Option<Vec<String>>>, groups: impl Into<Option<Vec<String>>>, clients: impl Into<Option<Vec<String>>>, owner: impl Into<Option<String>>, logic: impl Into<Option<Uma2PermissionLogic>>, decision_strategy: impl Into<Option<Uma2PermissionDecisionStrategy>> ) -> Result<Uma2PermissionAssociation, ClientError>

Used when permissions can be set to resources by resource servers on behalf of their users

§Arguments
  • token This API is protected by a bearer token that must represent a consent granted by the user to the resource server to manage permissions on his behalf. The bearer token can be a regular access token obtained from the token endpoint using: - Resource Owner Password Credentials Grant Type - Token Exchange, in order to exchange an access token granted to some client (public client) for a token where audience is the resource server
  • resource_id Resource ID to be protected
  • name Name for the permission
  • description Description for the permission
  • scopes A list of scopes given on this resource to the user if the permission validates
  • roles Give the permission to users in a list of roles
  • groups Give the permission to users in a list of groups
  • clients Give the permission to users using a specific list of clients
  • owner Give the permission to the owner
  • logic Positive: If the user is in the required groups/roles or using the right client, then give the permission to the user. Negative - the inverse
  • decision_strategy Go through the required conditions. If it is more than one condition, give the permission to the user if the following conditions are met: - Unanimous: The default strategy if none is provided. In this case, all policies must evaluate to a positive decision for the final decision to be also positive. - Affirmative: In this case, at least one policy must evaluate to a positive decision in order for the final decision to be also positive. - Consensus: In this case, the number of positive decisions must be greater than the number of negative decisions. If the number of positive and negative decisions is the same, the final decision will be negative
source

pub async fn update_uma2_resource_permission( &self, id: String, token: String, name: String, description: String, scopes: Vec<String>, roles: impl Into<Option<Vec<String>>>, groups: impl Into<Option<Vec<String>>>, clients: impl Into<Option<Vec<String>>>, owner: impl Into<Option<String>>, logic: impl Into<Option<Uma2PermissionLogic>>, decision_strategy: impl Into<Option<Uma2PermissionDecisionStrategy>> ) -> Result<Uma2PermissionAssociation, ClientError>

Update a UMA2 resource’s associated permission

§Arguments
  • id The ID of the the associated permission
  • token This API is protected by a bearer token that must represent a consent granted by the user to the resource server to manage permissions on his behalf. The bearer token can be a regular access token obtained from the token endpoint using: - Resource Owner Password Credentials Grant Type - Token Exchange, in order to exchange an access token granted to some client (public client) for a token where audience is the resource server
  • name Name for the permission
  • description Description for the permission
  • scopes A list of scopes given on this resource to the user if the permission validates
  • roles Give the permission to users in a list of roles
  • groups Give the permission to users in a list of groups
  • clients Give the permission to users using a specific list of clients
  • owner Give the permission to the owner
  • logic Positive: If the user is in the required groups/roles or using the right client, then give the permission to the user. Negative - the inverse
  • decision_strategy Go through the required conditions. If it is more than one condition, give the permission to the user if the following conditions are met: - Unanimous: The default strategy if none is provided. In this case, all policies must evaluate to a positive decision for the final decision to be also positive. - Affirmative: In this case, at least one policy must evaluate to a positive decision in order for the final decision to be also positive. - Consensus: In this case, the number of positive decisions must be greater than the number of negative decisions. If the number of positive and negative decisions is the same, the final decision will be negative
source

pub async fn delete_uma2_resource_permission( &self, id: String, token: String ) -> Result<(), ClientError>

Delete a UMA2 resource’s permission

§Arguments
  • id The ID of the resource permission
  • token This API is protected by a bearer token that must represent a consent granted by the user to the resource server to manage permissions on his behalf. The bearer token can be a regular access token obtained from the token endpoint using: - Resource Owner Password Credentials Grant Type - Token Exchange, in order to exchange an access token granted to some client (public client) for a token where audience is the resource server
source

pub async fn search_for_uma2_resource_permission( &self, token: String, resource: impl Into<Option<String>>, name: impl Into<Option<String>>, scope: impl Into<Option<String>>, offset: impl Into<Option<u32>>, count: impl Into<Option<u32>> ) -> Result<Vec<Uma2PermissionAssociation>, ClientError>

Search for UMA2 resource associated permissions

§Arguments
  • token This API is protected by a bearer token that must represent a consent granted by the user to the resource server to manage permissions on his behalf. The bearer token can be a regular access token obtained from the token endpoint using: - Resource Owner Password Credentials Grant Type - Token Exchange, in order to exchange an access token granted to some client (public client) for a token where audience is the resource server
  • resource Search by resource id
  • name Search by name
  • scope Search by scope
  • offset Skip n amounts of permissions.
  • count Max amount of permissions to return. Should be used especially with large return sets
source§

impl<P, C> Client<P, C>

source

pub async fn create_uma2_resource( &self, pat_token: String, name: String, resource_type: impl Into<Option<String>>, icon_uri: impl Into<Option<String>>, resource_scopes: impl Into<Option<Vec<String>>>, display_name: impl Into<Option<String>>, owner: impl Into<Option<Uma2Owner>>, owner_managed_access: impl Into<Option<bool>> ) -> Result<Uma2Resource, ClientError>

Create a UMA2 managed resource

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the uma_protection scope defined
  • name User readable name for this resource.
  • resource_type The type of resource. Helps to categorise resources
  • icon_uri User visible icon’s URL
  • resource_scopes A list of scopes attached to this resource
  • description A readable description
  • owner Resource server is the default user, unless this value is set. Can be the username of the user or its server identifier
  • owner_managed_access Whether to allow user managed access of this resource
source

pub async fn update_uma2_resource( &self, pat_token: String, name: String, resource_type: Option<String>, icon_uri: Option<String>, resource_scopes: Option<Vec<String>>, display_name: Option<String>, owner: Option<Uma2Owner>, owner_managed_access: Option<bool> ) -> Result<Uma2Resource, ClientError>

Update a UMA2 managed resource

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the uma_protection scope defined
  • name User readable name for this resource.
  • resource_type The type of resource. Helps to categorise resources
  • icon_uri User visible icon’s URL
  • resource_scopes A list of scopes attached to this resource
  • description A readable description
  • owner Resource server is the default user, unless this value is set. Can be the username of the user or its server identifier
  • owner_managed_access Whether to allow user managed access of this resource
source

pub async fn delete_uma2_resource( &self, pat_token: String, id: String ) -> Result<(), ClientError>

Deletes a UMA2 managed resource

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the
  • id The server identifier of the resource
source

pub async fn get_uma2_resource_by_id( &self, pat_token: String, id: String ) -> Result<Uma2Resource, ClientError>

Get a UMA2 managed resource by its identifier

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the
  • id The server identifier of the resource
source

pub async fn search_for_uma2_resources( &self, pat_token: String, name: impl Into<Option<String>>, uri: impl Into<Option<String>>, owner: impl Into<Option<String>>, resource_type: impl Into<Option<String>>, scope: impl Into<Option<String>> ) -> Result<Vec<String>, ClientError>

Search for a UMA2 resource

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the
  • name Search by the resource’s name
  • uri Search by the resource’s uri
  • owner Search by the resource’s owner
  • resource_type Search by the resource’s type
  • scope Search by the resource’s scope
source§

impl<P, C> Client<P, C>

source

pub async fn obtain_requesting_party_token( &self, token: String, auth_method: Uma2AuthenticationMethod, ticket: impl Into<Option<String>>, claim_token: impl Into<Option<String>>, claim_token_format: impl Into<Option<Uma2ClaimTokenFormat>>, rpt: impl Into<Option<String>>, permission: impl Into<Option<Vec<String>>>, audience: impl Into<Option<String>>, response_include_resource_name: impl Into<Option<bool>>, response_permissions_limit: impl Into<Option<u32>>, submit_request: impl Into<Option<bool>> ) -> Result<String, ClientError>

Obtain an RPT from a UMA2 compliant OIDC server

§Arguments
  • token Bearer token to do the RPT call
  • ticket The most recent permission ticket received by the client as part of the UMA authorization process
  • claim_token A string representing additional claims that should be considered by the server when evaluating permissions for the resource(s) and scope(s) being requested.
  • claim_token_format urn:ietf:params:oauth:token-type:jwt or https://openid.net/specs/openid-connect-core-1_0.html#IDToken
  • rpt A previously issued RPT which permissions should also be evaluated and added in a new one. This parameter allows clients in possession of an RPT to perform incremental authorization where permissions are added on demand.
  • permission String representing a set of one or more resources and scopes the client is seeking access. This parameter can be defined multiple times in order to request permission for multiple resource and scopes. This parameter is an extension to urn:ietf:params:oauth:grant-type:uma-ticket grant type in order to allow clients to send authorization requests without a permission ticket
  • audience The client identifier of the resource server to which the client is seeking access. This parameter is mandatory in case the permission parameter is defined
  • response_include_resource_name A boolean value indicating to the server whether resource names should be included in the RPT’s permissions. If false, only the resource identifier is included
  • response_permissions_limit An integer N that defines a limit for the amount of permissions an RPT can have. When used together with rpt parameter, only the last N requested permissions will be kept in the RPT.
  • submit_request A boolean value indicating whether the server should create permission requests to the resources and scopes referenced by a permission ticket. This parameter only have effect if used together with the ticket parameter as part of a UMA authorization process
source

pub async fn create_uma2_permission_ticket( &self, pat_token: String, requests: Vec<Uma2PermissionTicketRequest> ) -> Result<Uma2PermissionTicketResponse, ClientError>

Create a permission ticket. A permission ticket is a special security token type representing a permission request. Per the UMA specification, a permission ticket is: A correlation handle that is conveyed from an authorization server to a resource server, from a resource server to a client, and ultimately from a client back to an authorization server, to enable the authorization server to assess the correct policies to apply to a request for authorization data.

§Arguments
  • pat_token A Protection API token (PAT) is like any OAuth2 token, but should have the
  • requests A list of resources, optionally with their scopes, optionally with extra claims to be processed.

Trait Implementations§

source§

impl<C: CompactJson + Claims, P: Clone> Clone for Client<P, C>

Implement clone if the provider can be cloned.

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<P: Debug, C: Debug + CompactJson + Claims> Debug for Client<P, C>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<P, C> Freeze for Client<P, C>
where P: Freeze,

§

impl<P = Discovered, C = StandardClaims> !RefUnwindSafe for Client<P, C>

§

impl<P, C> Send for Client<P, C>
where P: Send, C: Send,

§

impl<P, C> Sync for Client<P, C>
where P: Sync, C: Sync,

§

impl<P, C> Unpin for Client<P, C>
where P: Unpin, C: Unpin,

§

impl<P = Discovered, C = StandardClaims> !UnwindSafe for Client<P, C>

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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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> ToOwned for T
where T: Clone,

§

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

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

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