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>
impl<C: CompactJson + Claims> Client<Discovered, C>
source§impl<C: CompactJson + Claims, P: Provider + Configurable> Client<P, C>
impl<C: CompactJson + Claims, P: Provider + Configurable> Client<P, C>
sourcepub fn redirect_url(&self) -> &str
pub fn redirect_url(&self) -> &str
Passthrough to the redirect_url stored in inth_oauth2 as a str.
sourcepub fn config(&self) -> &Config
pub fn config(&self) -> &Config
A reference to the config document of the provider obtained via discovery
sourcepub fn auth_url(&self, options: &Options) -> Url
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.
sourcepub async fn authenticate(
&self,
auth_code: &str,
nonce: impl Into<Option<&str>>,
max_age: impl Into<Option<&Duration>>
) -> Result<Token<C>, Error>
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.
sourcepub fn decode_token<T: CompactJson>(
&self,
token: &mut IdToken<T>
) -> Result<(), Error>
pub fn decode_token<T: CompactJson>( &self, token: &mut IdToken<T> ) -> Result<(), Error>
Mutates a Compact::encoded Token to Compact::decoded.
§Errors
- Decode::MissingKid if the keyset has multiple keys but the key id on the token is missing
- Decode::MissingKey if the given key id is not in the key set
- Decode::EmptySet if the keyset is empty
- Jose::WrongKeyType if the alg of the key and the alg in the token header mismatch
- Jose::WrongKeyType if the specified key alg isn’t a signature algorithm
- Decode::UnsupportedEllipticCurve if the alg is cryptographic curve
- Decode::UnsupportedOctetKeyPair if the alg is octet key pair
- Error::Jose error if decoding fails
sourcepub 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>
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
- Error::Jose Error if the Token isn’t decoded
- Error::Validation::Mismatch::Issuer if the provider issuer and token issuer mismatch
- Error::Validation::Mismatch::Nonce if a given nonce and the token nonce mismatch
- Error::Validation::Missing::Nonce if args has a nonce and the token does not
- Error::Validation::Missing::Audience if the token aud doesn’t contain the client id
- Error::Validation::Missing::AuthorizedParty if there are multiple audiences and azp is missing
- Error::Validation::Mismatch::AuthorizedParty if the azp is not the client_id
- Error::Validation::Expired::Expires if the current time is past the expiration time
- Error::Validation::Expired::MaxAge is the token is older than the provided max_age
- Error::Validation::Missing::AuthTime if a max_age was given and the token has no auth time
sourcepub async fn request_userinfo(
&self,
token: &Token<C>
) -> Result<Userinfo, Error>
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
- ErrorUserinfo::NoUrl if this provider doesn’t have a userinfo endpoint
- Error::Insecure if the userinfo url is not https
- Error::Jose if the token is not decoded
- Error::Http if something goes wrong getting the document
- Error::Json if the response is not a valid Userinfo document
- ErrorUserinfo::MissingSubject if subject (sub) is missing
- ErrorUserinfo::MismatchSubject if the returned userinfo document and tokens subject mismatch
sourcepub async fn request_userinfo_custom<U>(
&self,
token: &Token<C>
) -> Result<U, Error>where
U: StandardClaimsSubject,
pub async fn request_userinfo_custom<U>(
&self,
token: &Token<C>
) -> Result<U, Error>where
U: StandardClaimsSubject,
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
- ErrorUserinfo::NoUrl if this provider doesn’t have a userinfo endpoint
- Error::Insecure if the userinfo url is not https
- Decode::MissingKid if the keyset has multiple keys but the key id on the token is missing
- Decode::MissingKey if the given key id is not in the key set
- Decode::EmptySet if the keyset is empty
- Jose::WrongKeyType if the alg of the key and the alg in the token header mismatch
- Jose::WrongKeyType if the specified key alg isn’t a signature algorithm
- Error::Jose if the token is not decoded
- Error::Http if something goes wrong getting the document
- Error::Json if the response is not a valid Userinfo document
- ErrorUserinfo::MissingSubject if subject (sub) is missing
- ErrorUserinfo::MismatchSubject if the returned userinfo document and tokens subject mismatch
- ErrorUserinfo::MissingContentType if content-type header is missing
- ErrorUserinfo::ParseContentType if content-type header is not parsable
- ErrorUserinfo::WrongContentType if content-type header is not accepted
§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>
impl<P, C> Client<P, C>
sourcepub 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
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,
);
sourcepub fn auth_uri<'scope, 'state>(
&self,
scope: impl Into<Option<&'scope str>>,
state: impl Into<Option<&'state str>>
) -> Url
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.
§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,
);
sourcepub async fn request_token(&self, code: &str) -> Result<Bearer, ClientError>
pub async fn request_token(&self, code: &str) -> Result<Bearer, ClientError>
Requests an access token using an authorization code.
sourcepub async fn request_token_using_password_credentials(
&self,
username: &str,
password: &str,
scope: impl Into<Option<&str>>
) -> Result<Bearer, ClientError>
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
sourcepub async fn request_token_using_client_credentials(
&self,
scope: impl Into<Option<&str>>
) -> Result<Bearer, ClientError>
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
sourcepub async fn refresh_token(
&self,
token: impl AsRef<Bearer>,
scope: impl Into<Option<&str>>
) -> Result<Bearer, ClientError>
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.
sourcepub async fn ensure_token(
&self,
token_guard: TemporalBearerGuard
) -> Result<TemporalBearerGuard, ClientError>
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>
impl<C: CompactJson + Claims> Client<DiscoveredUma2, C>
source§impl<P, C> Client<P, C>
impl<P, C> Client<P, C>
sourcepub 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>
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 serverresource_id
Resource ID to be protectedname
Name for the permissiondescription
Description for the permissionscopes
A list of scopes given on this resource to the user if the permission validatesroles
Give the permission to users in a list of rolesgroups
Give the permission to users in a list of groupsclients
Give the permission to users using a specific list of clientsowner
Give the permission to the ownerlogic
Positive: If the user is in the required groups/roles or using the right client, then give the permission to the user. Negative - the inversedecision_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
sourcepub 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>
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 permissiontoken
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 servername
Name for the permissiondescription
Description for the permissionscopes
A list of scopes given on this resource to the user if the permission validatesroles
Give the permission to users in a list of rolesgroups
Give the permission to users in a list of groupsclients
Give the permission to users using a specific list of clientsowner
Give the permission to the ownerlogic
Positive: If the user is in the required groups/roles or using the right client, then give the permission to the user. Negative - the inversedecision_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
sourcepub async fn delete_uma2_resource_permission(
&self,
id: String,
token: String
) -> Result<(), ClientError>
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 permissiontoken
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
sourcepub 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>
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 serverresource
Search by resource idname
Search by namescope
Search by scopeoffset
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>
impl<P, C> Client<P, C>
sourcepub 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>
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 definedname
User readable name for this resource.resource_type
The type of resource. Helps to categorise resourcesicon_uri
User visible icon’s URLresource_scopes
A list of scopes attached to this resourcedescription
A readable descriptionowner
Resource server is the default user, unless this value is set. Can be the username of the user or its server identifierowner_managed_access
Whether to allow user managed access of this resource
sourcepub 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>
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 definedname
User readable name for this resource.resource_type
The type of resource. Helps to categorise resourcesicon_uri
User visible icon’s URLresource_scopes
A list of scopes attached to this resourcedescription
A readable descriptionowner
Resource server is the default user, unless this value is set. Can be the username of the user or its server identifierowner_managed_access
Whether to allow user managed access of this resource
sourcepub async fn delete_uma2_resource(
&self,
pat_token: String,
id: String
) -> Result<(), ClientError>
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 theid
The server identifier of the resource
sourcepub async fn get_uma2_resource_by_id(
&self,
pat_token: String,
id: String
) -> Result<Uma2Resource, ClientError>
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 theid
The server identifier of the resource
sourcepub 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>
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 thename
Search by the resource’s nameuri
Search by the resource’s uriowner
Search by the resource’s ownerresource_type
Search by the resource’s typescope
Search by the resource’s scope
source§impl<P, C> Client<P, C>
impl<P, C> Client<P, C>
sourcepub 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>
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 callticket
The most recent permission ticket received by the client as part of the UMA authorization processclaim_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#IDTokenrpt
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 ticketaudience
The client identifier of the resource server to which the client is seeking access. This parameter is mandatory in case the permission parameter is definedresponse_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 includedresponse_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
sourcepub async fn create_uma2_permission_ticket(
&self,
pat_token: String,
requests: Vec<Uma2PermissionTicketRequest>
) -> Result<Uma2PermissionTicketResponse, ClientError>
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 therequests
A list of resources, optionally with their scopes, optionally with extra claims to be processed.