[][src]Crate oauth2

A simple implementation of the OAuth2 flow, trying to adhere as much as possible to RFC 6749.

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

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;

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

Async API

An asynchronous API is also provided.

In order to use futures 0.1, include the oauth2 crate like this:

[dependencies]
oauth2 = { version = "<desired version>", features = ["features-01"] }

Example

use failure;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::future_http_client;
use tokio::runtime::Runtime;
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()),
        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.

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;

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

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;

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

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;

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

Async/Await API

An asynchronous API for async/await is also provided. In order to use futures 0.3, include the oauth2 crate like this:

[dependencies.oauth2]
version = "<desired version>"
features = ["futures-03"]
default-features = false

Example

use failure;
use oauth2::{
    AsyncCodeTokenRequest,
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::async_http_client;
use url::Url;
use async_std::task;

// 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 = task::block_on(async {
    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.

Other examples

More specific implementations are available as part of the examples:

Modules

basic

Basic OAuth2 implementation with no extensions (RFC 6749).

helpers

Helper methods used by OAuth2 implementations/extensions.

reqwest

HTTP client backed by the reqwest crate.

Structs

AccessToken

Access token returned by the token endpoint and used to access protected resources.

AuthUrl

URL of the authorization server's authorization endpoint.

AuthorizationCode

Authorization code returned from the authorization endpoint.

AuthorizationRequest

A request to the authorization endpoint

Client

Stores the configuration for an OAuth2 client.

ClientCredentialsTokenRequest

A request to exchange client credentials for an access token.

ClientId

Client identifier issued to the client during the registration process described by Section 2.2.

ClientSecret

Client password issued to the client during the registration process described by Section 2.2.

CodeTokenRequest

A request to exchange an authorization code for an access token.

CsrfToken

Value used for CSRF protection via the state parameter.

EmptyExtraTokenFields

Empty (default) extra token fields.

HttpRequest

An HTTP request.

HttpResponse

An HTTP response.

PasswordTokenRequest

A request to exchange resource owner credentials for an access token.

PkceCodeChallenge

Code Challenge used for PKCE protection via the code_challenge parameter.

PkceCodeChallengeMethod

Code Challenge Method used for PKCE protection via the code_challenge_method parameter.

PkceCodeVerifier

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 "-" / "." / "_" / "~".

RedirectUrl

URL of the client's redirection endpoint.

RefreshToken

Refresh token used to obtain a new access token (if supported by the authorization server).

RefreshTokenRequest

A request to exchange a refresh token for an access token.

ResourceOwnerPassword

Resource owner's password used directly as an authorization grant to obtain an access token.

ResourceOwnerUsername

Resource owner's username used directly as an authorization grant to obtain an access token.

ResponseType

Authorization endpoint response (grant) type defined in Section 3.1.1.

Scope

Access token scope, as defined by the authorization server.

StandardErrorResponse

Error response returned by server after requesting an access token.

StandardTokenResponse

Standard OAuth2 token response.

TokenUrl

URL of the authorization server's token endpoint.

Enums

AuthType

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.

RequestTokenError

Error encountered while requesting access token.

Traits

ErrorResponse

Server Error Response

ErrorResponseType

Error types enum.

ExtraTokenFields

Trait for adding extra fields to the TokenResponse.

TokenResponse

Common methods shared by all OAuth2 token implementations.

TokenType

Trait for OAuth2 access tokens.