39 releases (8 stable)

✓ Uses Rust 2018 edition

new 3.0.0-alpha.9 Jan 23, 2020
3.0.0-alpha.7 Dec 8, 2019
3.0.0-alpha.6 Nov 27, 2019
3.0.0-alpha.3 Jul 4, 2019
0.1.1 Dec 16, 2014
Download history 1131/week @ 2019-10-13 404/week @ 2019-10-20 286/week @ 2019-10-27 310/week @ 2019-11-03 250/week @ 2019-11-10 437/week @ 2019-11-17 512/week @ 2019-11-24 782/week @ 2019-12-01 1468/week @ 2019-12-08 1023/week @ 2019-12-15 342/week @ 2019-12-22 422/week @ 2019-12-29 617/week @ 2020-01-05 1011/week @ 2020-01-12 535/week @ 2020-01-19

2,621 downloads per month
Used in 14 crates

MIT/Apache

165KB
3.5K SLoC

OAuth2

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

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


lib.rs:

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

Contents

Importing oauth2: selecting an HTTP client interface

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

  • Synchronous (blocking)

    The synchronous interface is available for any combination of feature flags.

    Example import in Cargo.toml:

    oauth2 = "3.0"
    
  • Asynchronous via futures 0.1

    Support is enabled via the futures-01 feature flag.

    Example import in Cargo.toml:

    oauth2 = { version = "3.0", features = ["futures-01"] }
    
  • Async/await via futures 0.3

    Support is enabled via the futures-03 feature flag. Typically, the default support for reqwest 0.9 is also disabled when using async/await. If desired, the reqwest-010 feature flag can be used to enable reqwest 0.10 and its async/await client interface.

    Example import in Cargo.toml:

    oauth2 = { version = "3.0", features = ["futures-03"], default-features = false }
    

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

  • [reqwest]

    The reqwest HTTP client supports all three modes. By default, reqwest 0.9 is enabled, which supports the synchronous and asynchronous futures 0.1 APIs.

    Synchronous client: [reqwest::http_client]

    Asynchronous futures 0.1 client: [reqwest::future_http_client]

    Async/await futures 0.3 client: [reqwest::async_http_client]. This mode requires reqwest 0.10, which can be enabled via the reqwest-010 feature flag. Typically, the default features are also disabled (default-features = false in Cargo.toml) to remove the dependency on reqwest 0.9 when using reqwest 0.10. However, both can be used together if both asynchronous interfaces are desired.

  • [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]

  • 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 0.9 dependency by specifying default-features = false in Cargo.toml:

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

    Synchronous HTTP clients should implement the following trait:

    FnOnce(HttpRequest) -> Result<HttpResponse, RE>
    where RE: failure::Fail
    

    Asynchronous futures 0.1 HTTP clients should implement the following trait:

    FnOnce(HttpRequest) -> F
    where
      F: Future<Item = HttpResponse, Error = RE>,
      RE: failure::Fail
    

    Async/await futures 0.3 HTTP clients should implement the following trait:

    FnOnce(HttpRequest) -> F + Send
    where
      F: Future<Output = Result<HttpResponse, RE>> + Send,
      RE: failure::Fail
    

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 0.9.

use failure;
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<(), failure::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_url(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 (futures 0.1-based) API

In order to use futures 0.1, include oauth2 as follows:

[dependencies]
oauth2 = { version = "3.0", features = ["futures-01"] }
use failure;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
# #[cfg(all(feature = "futures-01", any(feature = "reqwest-09", feature = "reqwest-010")))]
use oauth2::reqwest::future_http_client;
use tokio::runtime::Runtime;
use url::Url;

# #[cfg(all(feature = "futures-01", any(feature = "reqwest-09", feature = "reqwest-010")))]
# fn err_wrapper() -> Result<(), failure::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_url(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`.

let mut runtime = Runtime::new().unwrap();
// Now you can trade it for an access token.
let token_result =
    runtime.block_on(
        client
            .exchange_code(AuthorizationCode::new("some authorization code".to_string()))
            // Set the PKCE code verifier.
            .set_pkce_verifier(pkce_verifier)
            .request_future(future_http_client)
    )?;

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

Example: Async/Await API

Async/await support requires rustc 1.39.0 or newer. In order to use async/await, include oauth2 as follows:

[dependencies]
oauth2 = { version = "3.0", features = ["futures-03", "reqwest-010"], default-features = false }
use failure;
# #[cfg(feature = "futures-03")]
use oauth2::{
    AsyncCodeTokenRequest,
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
# #[cfg(all(feature = "futures-03", feature = "reqwest-010"))]
use oauth2::reqwest::async_http_client;
use url::Url;

# #[cfg(all(feature = "futures-03", feature = "reqwest-010"))]
# async fn err_wrapper() -> Result<(), failure::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_url(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 failure;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    RedirectUrl,
    Scope
};
use oauth2::basic::BasicClient;
use url::Url;

# fn err_wrapper() -> Result<(), failure::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 failure;
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<(), failure::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 failure;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use url::Url;

# fn err_wrapper() -> Result<(), failure::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(())
# }

Other examples

More specific implementations are available as part of the examples:

Contributed Examples

Dependencies

~15MB
~315K SLoC