Expand description
An extensible, strongly-typed implementation of OAuth2 (RFC 6749) including token introspection (RFC 7662) and token revocation (RFC 7009).
§Contents
- Importing
oauth2
: selecting an HTTP client interface - Getting started: Authorization Code Grant w/ PKCE
- Implicit Grant
- Resource Owner Password Credentials Grant
- Client Credentials Grant
- Device Authorization Flow
- Other examples
§Importing oauth2
: selecting an HTTP client interface
This library offers a flexible HTTP client interface with two modes:
-
Synchronous (blocking)
NOTE: Be careful not to use a blocking HTTP client within
async
Rust code, which may panic or cause other issues. Thetokio::task::spawn_blocking
function may be useful in this situation. -
Asynchronous
§Security Warning
To prevent
SSRF
vulnerabilities, be sure to configure the HTTP client not to follow redirects. For example,
use redirect::Policy::none
when using
reqwest
, or redirects(0)
when using [ureq
].
§HTTP Clients
For the HTTP client modes described above, the following HTTP client implementations can be used:
-
The
reqwest
HTTP client supports both the synchronous and asynchronous modes and is enabled by default.Synchronous client: [
reqwest::blocking::Client
] (requires thereqwest-blocking
feature flag)Asynchronous client:
reqwest::Client
(requires either thereqwest
orreqwest-blocking
feature flags) -
The
curl
HTTP client only supports the synchronous HTTP client mode and can be enabled inCargo.toml
via thecurl
feature flag.Synchronous client:
oauth2::CurlHttpClient
-
The
ureq
HTTP client is a simple HTTP client with minimal dependencies. It only supports the synchronous HTTP client mode and can be enabled inCargo.toml
via theureq
feature flag.Synchronous client: [
ureq::Agent
] -
Custom
In addition to the clients above, users may define their own HTTP clients, which must accept an
HttpRequest
and return anHttpResponse
or error. Users writing their own clients may wish to disable the defaultreqwest
dependency by specifyingdefault-features = false
inCargo.toml
(replacing...
with the desired version of this crate):oauth2 = { version = "...", default-features = false }
Synchronous HTTP clients should implement the
SyncHttpClient
trait, which is automatically implemented for any function/closure that implements:ⓘFn(HttpRequest) -> Result<HttpResponse, E> where E: std::error::Error + 'static
Asynchronous HTTP clients should implement the
AsyncHttpClient
trait, which is automatically implemented for any function/closure that implements:ⓘFn(HttpRequest) -> F where E: std::error::Error + 'static, F: Future<Output = Result<HttpResponse, E>>,
§Comparing secrets securely
OAuth flows require comparing secrets received from the provider servers. To do so securely
while avoiding timing side-channels, the
comparison must be done in constant time, either using a constant-time crate such as
constant_time_eq
(which could break if a future
compiler version decides to be overly smart
about its optimizations), or by first computing a cryptographically-secure hash (e.g., SHA-256)
of both values and then comparing the hashes using ==
.
The timing-resistant-secret-traits
feature flag adds a safe (but comparatively expensive)
PartialEq
implementation to the secret types. Timing side-channels are why PartialEq
is
not auto-derived for this crate’s secret types, and the lack of PartialEq
is intended to
prompt users to think more carefully about these comparisons.
§Getting started: Authorization Code Grant w/ PKCE
This is the most common OAuth2 flow. PKCE is recommended whenever the OAuth2 client has no client secret or has a client secret that cannot remain confidential (e.g., native, mobile, or client-side web applications).
§Example: Synchronous (blocking) API
This example works with oauth2
’s default feature flags, which include reqwest
.
use oauth2::{
AuthorizationCode,
AuthUrl,
ClientId,
ClientSecret,
CsrfToken,
PkceCodeChallenge,
RedirectUrl,
Scope,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use url::Url;
// Create an OAuth2 client by specifying the client ID, client secret, authorization URL and
// token URL.
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_client_secret(ClientSecret::new("client_secret".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?)
.set_token_uri(TokenUrl::new("http://token".to_string())?)
// Set the URL the user will be redirected to after the authorization process.
.set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?);
// Generate a PKCE challenge.
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
// Generate the full authorization URL.
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
// Set the desired scopes.
.add_scope(Scope::new("read".to_string()))
.add_scope(Scope::new("write".to_string()))
// Set the PKCE code challenge.
.set_pkce_challenge(pkce_challenge)
.url();
// This is the URL you should redirect the user to, in order to trigger the authorization
// process.
println!("Browse to: {}", auth_url);
// Once the user has been redirected to the redirect URL, you'll have access to the
// authorization code. For security reasons, your code should verify that the `state`
// parameter returned by the server matches `csrf_token`.
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("Client should build");
// Now you can trade it for an access token.
let token_result =
client
.exchange_code(AuthorizationCode::new("some authorization code".to_string()))
// Set the PKCE code verifier.
.set_pkce_verifier(pkce_verifier)
.request(&http_client)?;
// Unwrapping token_result will either produce a Token or a RequestTokenError.
§Example: Asynchronous API
The example below uses async/await:
use oauth2::{
AuthorizationCode,
AuthUrl,
ClientId,
ClientSecret,
CsrfToken,
PkceCodeChallenge,
RedirectUrl,
Scope,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use url::Url;
// Create an OAuth2 client by specifying the client ID, client secret, authorization URL and
// token URL.
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_client_secret(ClientSecret::new("client_secret".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?)
.set_token_uri(TokenUrl::new("http://token".to_string())?)
// Set the URL the user will be redirected to after the authorization process.
.set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?);
// Generate a PKCE challenge.
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
// Generate the full authorization URL.
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
// Set the desired scopes.
.add_scope(Scope::new("read".to_string()))
.add_scope(Scope::new("write".to_string()))
// Set the PKCE code challenge.
.set_pkce_challenge(pkce_challenge)
.url();
// This is the URL you should redirect the user to, in order to trigger the authorization
// process.
println!("Browse to: {}", auth_url);
// Once the user has been redirected to the redirect URL, you'll have access to the
// authorization code. For security reasons, your code should verify that the `state`
// parameter returned by the server matches `csrf_token`.
let http_client = reqwest::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("Client should build");
// Now you can trade it for an access token.
let token_result = client
.exchange_code(AuthorizationCode::new("some authorization code".to_string()))
// Set the PKCE code verifier.
.set_pkce_verifier(pkce_verifier)
.request_async(&http_client)
.await?;
// Unwrapping token_result will either produce a Token or a RequestTokenError.
§Implicit Grant
This flow fetches an access token directly from the authorization endpoint. Be sure to understand the security implications of this flow before using it. In most cases, the Authorization Code Grant flow is preferable to the Implicit Grant flow.
§Example
use oauth2::{
AuthUrl,
ClientId,
CsrfToken,
RedirectUrl,
Scope
};
use oauth2::basic::BasicClient;
use url::Url;
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?);
// Generate the full authorization URL.
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
.use_implicit_flow()
.url();
// This is the URL you should redirect the user to, in order to trigger the authorization
// process.
println!("Browse to: {}", auth_url);
// Once the user has been redirected to the redirect URL, you'll have the access code.
// For security reasons, your code should verify that the `state` parameter returned by the
// server matches `csrf_token`.
§Resource Owner Password Credentials Grant
You can ask for a password access token by calling the Client::exchange_password
method,
while including the username and password.
§Example
use oauth2::{
AuthUrl,
ClientId,
ClientSecret,
ResourceOwnerPassword,
ResourceOwnerUsername,
Scope,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use url::Url;
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_client_secret(ClientSecret::new("client_secret".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?)
.set_token_uri(TokenUrl::new("http://token".to_string())?);
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("Client should build");
let token_result =
client
.exchange_password(
&ResourceOwnerUsername::new("user".to_string()),
&ResourceOwnerPassword::new("pass".to_string())
)
.add_scope(Scope::new("read".to_string()))
.request(&http_client)?;
§Client Credentials Grant
You can ask for a client credentials access token by calling the
Client::exchange_client_credentials
method.
§Example
use oauth2::{
AuthUrl,
ClientId,
ClientSecret,
Scope,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use url::Url;
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_client_secret(ClientSecret::new("client_secret".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?)
.set_token_uri(TokenUrl::new("http://token".to_string())?);
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("Client should build");
let token_result = client
.exchange_client_credentials()
.add_scope(Scope::new("read".to_string()))
.request(&http_client)?;
§Device Authorization Flow
Device Authorization Flow allows users to sign in on browserless or input-constrained
devices. This is a two-stage process; first a user-code and verification
URL are obtained by using the Client::exchange_client_credentials
method. Those are displayed to the user, then are used in a second client
to poll the token endpoint for a token.
§Example
use oauth2::{
AuthUrl,
ClientId,
ClientSecret,
DeviceAuthorizationUrl,
Scope,
StandardDeviceAuthorizationResponse,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use url::Url;
let device_auth_url = DeviceAuthorizationUrl::new("http://deviceauth".to_string())?;
let client = BasicClient::new(ClientId::new("client_id".to_string()))
.set_client_secret(ClientSecret::new("client_secret".to_string()))
.set_auth_uri(AuthUrl::new("http://authorize".to_string())?)
.set_token_uri(TokenUrl::new("http://token".to_string())?)
.set_device_authorization_url(device_auth_url);
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("Client should build");
let details: StandardDeviceAuthorizationResponse = client
.exchange_device_code()
.add_scope(Scope::new("read".to_string()))
.request(&http_client)?;
println!(
"Open this URL in your browser:\n{}\nand enter the code: {}",
details.verification_uri().to_string(),
details.user_code().secret().to_string()
);
let token_result =
client
.exchange_device_access_token(&details)
.request(&http_client, std::thread::sleep, None)?;
§Other examples
More specific implementations are available as part of the examples:
- Google (includes token revocation)
- Github
- Microsoft Device Authorization Flow (async)
- Microsoft Graph
- Wunderlist
§Contributed Examples
actix-web-oauth2
(version 2.x of this crate)
Re-exports§
Modules§
- Basic OAuth2 implementation with no extensions (RFC 6749).
- Helper methods used by OAuth2 implementations/extensions.
Structs§
- Access token returned by the token endpoint and used to access protected resources.
- URL of the authorization server’s authorization endpoint.
- Authorization code returned from the authorization endpoint.
- A request to the authorization endpoint
- Stores the configuration for an OAuth2 client.
- A request to exchange client credentials for an access token.
- Client identifier issued to the client during the registration process described by Section 2.2.
- Client password issued to the client during the registration process described by Section 2.2.
- A request to exchange an authorization code for an access token.
- Value used for CSRF protection via the
state
parameter. - The request for a device access token from the authorization server.
- The request for a set of verification codes from the authorization server.
- Standard OAuth2 device authorization response.
- URL of the client’s device authorization endpoint.
- Device code returned by the device authorization endpoint and used to query the token endpoint.
- Empty (default) extra token fields.
- Empty (default) extra token fields.
- URL of the end-user verification URI on the authorization server.
- Typestate indicating that an endpoint may have been set and can be used via fallible methods.
- Typestate indicating that an endpoint has not been set and cannot be used.
- Typestate indicating that an endpoint has been set and is ready to be used.
- A request to introspect an access token.
- URL of the client’s RFC 7662 OAuth 2.0 Token Introspection endpoint.
- A request to exchange resource owner credentials for an access token.
- Code Challenge used for PKCE protection via the
code_challenge
parameter. - Code Challenge Method used for PKCE protection via the
code_challenge_method
parameter. - Code Verifier used for PKCE protection via the
code_verifier
parameter. The value must have a minimum length of 43 characters and a maximum length of 128 characters. Each character must be ASCII alphanumeric or one of the characters “-” / “.” / “_” / “~”. - URL of the client’s redirection endpoint.
- Refresh token used to obtain a new access token (if supported by the authorization server).
- A request to exchange a refresh token for an access token.
- Resource owner’s password used directly as an authorization grant to obtain an access token.
- Resource owner’s username used directly as an authorization grant to obtain an access token.
- Authorization endpoint response (grant) type defined in Section 3.1.1.
- A request to revoke a token via an
RFC 7009
compatible endpoint. - URL of the authorization server’s RFC 7009 token revocation endpoint.
- Access token scope, as defined by the authorization server.
- Error response returned by server after requesting an access token.
- Standard OAuth2 token introspection response.
- Standard OAuth2 token response.
- URL of the authorization server’s token endpoint.
- User code returned by the device authorization endpoint and used by the user to authorize at the verification URI.
- Verification URI returned by the device authorization endpoint and visited by the user to authorize. Contains the user code.
Enums§
- Indicates whether requests to the authorization server should use basic authentication or include the parameters in the request body for requests in which either is valid.
- There was a problem configuring the request.
- Basic access token error types.
- Error type returned by built-in HTTP clients when requests fail.
- Error encountered while requesting access token.
- OAuth 2.0 Token Revocation error response types.
- A token representation usable with authorization servers that support RFC 7009 token revocation.
Traits§
- An asynchronous (future-based) HTTP client.
- Typestate base trait indicating whether an endpoint has been configured via its corresponding setter.
- Server Error Response
- Error types enum.
- Trait for adding extra fields to the
DeviceAuthorizationResponse
. - Trait for adding extra fields to the
TokenResponse
. - A revocable token.
- A synchronous (blocking) HTTP client.
- Common methods shared by all OAuth2 token introspection implementations.
- Common methods shared by all OAuth2 token implementations.
- Type of OAuth2 access token.
Type Aliases§
- Error response specialization for device code OAuth2 implementation.
- An HTTP request.
- An HTTP response.
- Standard implementation of DeviceAuthorizationResponse which throws away extra received response fields.