Crate oauth2

source ·
Expand description

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

Getting started: Authorization Code Grant

This is the most common OAuth2 flow.

Example

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

use oauth2::prelude::*;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    ClientId,
    ClientSecret,
    CsrfToken,
    RedirectUrl,
    Scope,
    TokenUrl
};
use oauth2::basic::BasicClient;
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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    )
        // Set the desired scopes.
        .add_scope(Scope::new("read".to_string()))
        .add_scope(Scope::new("write".to_string()))

        // Set the URL the user will be redirected to after the authorization process.
        .set_redirect_url(RedirectUrl::new(Url::parse("http://redirect")?));

// Generate the full authorization URL.
let (auth_url, csrf_token) = client.authorize_url(CsrfToken::new_random);

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

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

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

use oauth2::prelude::*;
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(Url::parse("http://authorize")?),
        None
    );

// Generate the full authorization URL.
let (auth_url, csrf_token) = client.authorize_url_implicit(CsrfToken::new_random);

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

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

use oauth2::prelude::*;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    ResourceOwnerPassword,
    ResourceOwnerUsername,
    Scope,
    TokenUrl
};
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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    )
        .add_scope(Scope::new("read".to_string()));

let token_result =
    client.exchange_password(
        &ResourceOwnerUsername::new("user".to_string()),
        &ResourceOwnerPassword::new("pass".to_string())
    );

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::prelude::*;
use oauth2::{
    AuthUrl,
    ClientId,
    ClientSecret,
    Scope,
    TokenUrl
};
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(Url::parse("http://authorize")?),
        Some(TokenUrl::new(Url::parse("http://token")?))
    )
        .add_scope(Scope::new("read".to_string()));

let token_result = client.exchange_client_credentials();

Other examples

More specific implementations are available as part of the examples:

Modules

Basic OAuth2 implementation with no extensions (RFC 6749).
Helper methods used by OAuth2 implementations/extensions.
Insecure methods – not recommended for most applications.
Crate prelude that should be wildcard-imported by crate users.

Structs

Access token returned by the token endpoint and used to access protected resources.
URL of the authorization server’s authorization endpoint.
Authorization code returned from the authorization endpoint.
Stores the configuration for an OAuth2 client.
Client identifier issued to the client during the registration process described by Section 2.2.
Client password issued to the client during the registration process described by Section 2.2.
Value used for CSRF protection via the state parameter.
Empty (default) extra token fields.
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 “-” / “.” / “_” / “~”.
URL of the client’s redirection endpoint.
Refresh token used to obtain a new access token (if supported by the authorization server).
Resource owner’s password used directly as an authorization grant to obtain an access token.
Resource owner’s username used directly as an authorization grant to obtain an access token.
Authorization endpoint response (grant) type defined in Section 3.1.1.
Access token scope, as defined by the authorization server.
Common methods shared by all OAuth2 token implementations.
URL of the authorization server’s token endpoint.

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.
Error encountered while requesting access token.

Traits

Error types enum.
Trait for adding extra fields to the TokenResponse.
Trait for OAuth2 access tokens.