32 releases (7 stable)

3.0.0-alpha.3 Jul 4, 2019
2.0.0-beta.3 Jun 22, 2019
2.0.0-beta.1 Mar 30, 2019
2.0.0-alpha.3 Dec 9, 2018
0.1.1 Dec 16, 2014

#97 in Authentication

Download history 453/week @ 2019-03-21 242/week @ 2019-03-28 1182/week @ 2019-04-04 171/week @ 2019-04-11 174/week @ 2019-04-18 229/week @ 2019-04-25 197/week @ 2019-05-02 195/week @ 2019-05-09 291/week @ 2019-05-16 181/week @ 2019-05-23 186/week @ 2019-05-30 371/week @ 2019-06-06 186/week @ 2019-06-13 276/week @ 2019-06-20 252/week @ 2019-06-27

1,194 downloads per month
Used in 8 crates

MIT/Apache

139KB
3K SLoC

OAuth2

A simple implementation of the OAuth2 flow in Rust.

Documentation is available on docs.rs or check the examples.

Before upgrading make sure to check out the changelog.

Development

Build:

cargo build

Run tests:

cargo test

Release:

cargo package && cargo publish

lib.rs:

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

extern crate base64;
extern crate oauth2;
extern crate rand;
extern crate url;

use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use url::Url;

# extern crate failure;
# 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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    )
    // Set the URL the user will be redirected to after the authorization process.
    .set_redirect_url(RedirectUrl::new(Url::parse("http://redirect")?));

// 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(())
# }
# fn main() {}

Async API

An asyncronous API is also provided.

Example

extern crate base64;
extern crate oauth2;
extern crate rand;
extern crate tokio;
extern crate url;

use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    PkceCodeChallenge,
    RedirectUrl,
    Scope,
    TokenResponse,
    TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2::reqwest::async_http_client;
use tokio::runtime::Runtime;
use url::Url;

# extern crate failure;
# 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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    )
    // Set the URL the user will be redirected to after the authorization process.
    .set_redirect_url(RedirectUrl::new(Url::parse("http://redirect")?));

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

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

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:

extern crate base64;
extern crate oauth2;
extern crate rand;
extern crate url;

use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    RedirectUrl,
    Scope
};
use oauth2::basic::BasicClient;
use url::Url;

# extern crate failure;
# 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(Url::parse("http://authorize")?),
        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(())
# }
# fn main() {}

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

extern crate base64;
extern crate oauth2;
extern crate rand;
extern crate url;

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

# extern crate failure;
# 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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    );

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(())
# }
# fn main() {}

Client Credentials Grant

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

Example:

extern crate oauth2;
extern crate url;

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

# extern crate failure;
# 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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    );

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

Other examples

More specific implementations are available as part of the examples:

Dependencies

~13MB
~263K SLoC