Crate oauth2

source ·
Expand description

github crates.io docs.rs

An asynchronous OAuth2 flow implementation, trying to adhere as much as possible to RFC 6749.


§Examples

To see the library in action, you can go to one of our examples:

If you’ve checked out the project they can be run like this:

cargo run --manifest-path=examples/Cargo.toml --bin spotify --
    --client-id <client-id> --client-secret <client-secret>
cargo run --manifest-path=examples/Cargo.toml --bin google --
    --client-id <client-id> --client-secret <client-secret>
cargo run --manifest-path=examples/Cargo.toml --bin twitch --
    --client-id <client-id> --client-secret <client-secret>

Note: You need to configure your client integration to permit redirects to http://localhost:8080/api/auth/redirect for these to work. How this is done depends on the integration used.


§Authorization Code Grant

This is the most common OAuth2 flow.

use oauth2::*;
use url::Url;

pub struct ReceivedCode {
    pub code: AuthorizationCode,
    pub state: State,
}

let reqwest_client = reqwest::Client::new();

// Create an OAuth2 client by specifying the client ID, client secret,
// authorization URL and token URL.
let mut client = Client::new(
    "client_id",
    Url::parse("http://authorize")?,
    Url::parse("http://token")?
);

client.set_client_secret("client_secret");
// Set the URL the user will be redirected to after the authorization
// process.
client.set_redirect_url(Url::parse("http://redirect")?);
// Set the desired scopes.
client.add_scope("read");
client.add_scope("write");

// Generate the full authorization URL.
let state = State::new_random();
let auth_url = client.authorize_url(&state);

// 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 `state`.
let received: ReceivedCode = listen_for_code(8080).await?;

if received.state != state {
   panic!("CSRF token mismatch :(");
}

// Now you can trade it for an access token.
let token = client.exchange_code(received.code)
    .with_client(&reqwest_client)
    .execute::<StandardToken>()
    .await?;

§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 above is preferred to the Implicit Grant flow.

use oauth2::*;
use url::Url;

pub struct ReceivedCode {
    pub code: AuthorizationCode,
    pub state: State,
}

let mut client = Client::new(
    "client_id",
    Url::parse("http://authorize")?,
    Url::parse("http://token")?
);

client.set_client_secret("client_secret");

// Generate the full authorization URL.
let state = State::new_random();
let auth_url = client.authorize_url_implicit(&state);

// 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 `state`.
let received: ReceivedCode = get_code().await?;

if received.state != state {
    panic!("CSRF token mismatch :(");
}

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

use oauth2::*;
use url::Url;

let reqwest_client = reqwest::Client::new();

let mut client = Client::new(
    "client_id",
    Url::parse("http://authorize")?,
    Url::parse("http://token")?
);

client.set_client_secret("client_secret");
client.add_scope("read");

let token = client
    .exchange_password("user", "pass")
    .with_client(&reqwest_client)
    .execute::<StandardToken>()
    .await?;

§Client Credentials Grant

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

use oauth2::*;
use url::Url;

let reqwest_client = reqwest::Client::new();
let mut client = Client::new(
    "client_id",
    Url::parse("http://authorize")?,
    Url::parse("http://token")?
);

client.set_client_secret("client_secret");
client.add_scope("read");

let token_result = client.exchange_client_credentials()
    .with_client(&reqwest_client)
    .execute::<StandardToken>();

§Relationship to oauth2-rs

This is a fork of oauth2-rs.

The main differences are:

  • Removal of unnecessary type parameters on Client (see discussion here).
  • Only support one client implementation (reqwest).
  • Remove most newtypes except Scope and the secret ones since they made the API harder to use.

Modules§

  • Helper methods used by OAuth2 implementations/extensions.

Structs§

  • Access token returned by the token endpoint and used to access protected resources.
  • Authorization code returned from the authorization endpoint.
  • Stores the configuration for an OAuth2 client.
  • A request wrapped in a client, ready to be executed.
  • Client password issued to the client during the registration process described by Section 2.2.
  • Error response returned by server after requesting an access token.
  • Code Challenge Method used for PKCE protection via the code_challenge_method parameter.
  • Code Challenge used for PKCE protection via the code_challenge 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 “-” / “.” / “_” / “~”.
  • Refresh token used to obtain a new access token (if supported by the authorization server).
  • A token request that is in progress.
  • Resource owner’s password used directly as an authorization grant to obtain an access token.
  • Access token scope, as defined by the authorization server.
  • Standard OAuth2 token response.
  • Value used for CSRF protection via the state parameter.
  • A parsed URL record.

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.
  • These error types are defined in Section 5.2 of RFC 6749.
  • Error encountered while requesting access token.
  • Errors when creating new clients.
  • Basic OAuth2 authorization token types.

Traits§

  • Common methods shared by all OAuth2 token implementations.