#pkce

oauth2

An extensible, strongly-typed implementation of OAuth2

55 releases (16 stable)

4.3.0 Nov 8, 2022
4.2.3 Jul 12, 2022
4.2.0 Apr 30, 2022
4.1.0 Jul 5, 2021
0.1.1 Dec 16, 2014

#4 in Authentication

Download history 19835/week @ 2022-08-19 20753/week @ 2022-08-26 21186/week @ 2022-09-02 20127/week @ 2022-09-09 21357/week @ 2022-09-16 20791/week @ 2022-09-23 17521/week @ 2022-09-30 23307/week @ 2022-10-07 21726/week @ 2022-10-14 22549/week @ 2022-10-21 22556/week @ 2022-10-28 24388/week @ 2022-11-04 27779/week @ 2022-11-11 24479/week @ 2022-11-18 25283/week @ 2022-11-25 21103/week @ 2022-12-02

103,027 downloads per month
Used in 92 crates (63 directly)

MIT/Apache

260KB
5.5K SLoC

OAuth2

Build Status

An extensible, strongly-typed implementation of OAuth2 (RFC 6749).

Documentation is available on docs.rs. Release notes are available on GitHub.

Sponsorship

This project is sponsored by Unflakable, a service for tracking and quarantining flaky tests.


lib.rs:

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

This library offers a flexible HTTP client interface with two modes:

  • Synchronous (blocking)
  • Asynchronous

For the HTTP client modes described above, the following HTTP client implementations can be used:

  • [reqwest]

    The reqwest HTTP client supports both the synchronous and asynchronous modes and is enabled by default.

    Synchronous client: [reqwest::http_client]

    Asynchronous client: [reqwest::async_http_client]

  • [curl]

    The curl HTTP client only supports the synchronous HTTP client mode and can be enabled in Cargo.toml via the curl feature flag.

    Synchronous client: [curl::http_client]

  • [ureq]

    The ureq HTTP client is a simple HTTP client with minimal dependencies. It only supports the synchronous HTTP client mode and can be enabled in Cargo.toml via the ureq feature flag.

  • Custom

    In addition to the clients above, users may define their own HTTP clients, which must accept an [HttpRequest] and return an [HttpResponse] or error. Users writing their own clients may wish to disable the default reqwest dependency by specifying default-features = false in Cargo.toml (replacing ... with the desired version of this crate):

    oauth2 = { version = "...", default-features = false }
    

    Synchronous HTTP clients should implement the following trait:

    FnOnce(HttpRequest) -> Result<HttpResponse, RE>
    where RE: std::error::Error + 'static
    

    Asynchronous HTTP clients should implement the following trait:

    FnOnce(HttpRequest) -> F
    where
      F: Future<Output = Result<HttpResponse, RE>>,
      RE: std::error::Error + 'static
    

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 anyhow;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use url::Url;

# fn err_wrapper() -> Result<(), anyhow::Error> {
// 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()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        Some(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_state`.

// 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.
# Ok(())
# }

Example: Asynchronous API

The example below uses async/await:

use anyhow;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
# #[cfg(feature = "reqwest")]
use oauth2::reqwest::async_http_client;
use url::Url;

# #[cfg(feature = "reqwest")]
# async fn err_wrapper() -> Result<(), anyhow::Error> {
// 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()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        Some(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_state`.

// 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(async_http_client)
    .await?;

// Unwrapping token_result will either produce a Token or a RequestTokenError.
# Ok(())
# }

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 anyhow;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    RedirectUrl,
    Scope
};
use oauth2::basic::BasicClient;
use url::Url;

# fn err_wrapper() -> Result<(), anyhow::Error> {
let client =
    BasicClient::new(
        ClientId::new("client_id".to_string()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        None
    );

// 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_state`.

# Ok(())
# }

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 anyhow;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    ResourceOwnerPassword,
    ResourceOwnerUsername,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use url::Url;

# fn err_wrapper() -> Result<(), anyhow::Error> {
let client =
    BasicClient::new(
        ClientId::new("client_id".to_string()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        Some(TokenUrl::new("http://token".to_string())?)
    );

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)?;
# Ok(())
# }

Client Credentials Grant

You can ask for a client credentials access token by calling the Client::exchange_client_credentials method.

Example

use anyhow;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use url::Url;

# fn err_wrapper() -> Result<(), anyhow::Error> {
let client =
    BasicClient::new(
        ClientId::new("client_id".to_string()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        Some(TokenUrl::new("http://token".to_string())?),
    );

let token_result = client
    .exchange_client_credentials()
    .add_scope(Scope::new("read".to_string()))
    .request(http_client)?;
# Ok(())
# }

Device Code Flow

Device Code 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 anyhow;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    DeviceAuthorizationUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::devicecode::StandardDeviceAuthorizationResponse;
use oauth2::reqwest::http_client;
use url::Url;

# fn err_wrapper() -> Result<(), anyhow::Error> {
let device_auth_url = DeviceAuthorizationUrl::new("http://deviceauth".to_string())?;
let client =
    BasicClient::new(
        ClientId::new("client_id".to_string()),
        Some(ClientSecret::new("client_secret".to_string())),
        AuthUrl::new("http://authorize".to_string())?,
        Some(TokenUrl::new("http://token".to_string())?),
    )
    .set_device_authorization_url(device_auth_url);

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)?;

# Ok(())
# }

Other examples

More specific implementations are available as part of the examples:

Contributed Examples

Dependencies

~5–16MB
~328K SLoC