Crate rocket_oauth2

source ·
Expand description

rocket_oauth2

OAuth2 (RFC 6749) client implementation for Rocket applications.

Requirements

  • Rocket 0.5

API Stability

rocket_oauth2 is still in its early stages and the API is subject to heavy change in the future. semver is respected, but only the latest release will be actively maintained.

Features

  • Handles the Authorization Code Grant (RFC 6749, §4.1)
  • Built-in support for a few popular OAuth2 providers
  • Support for custom providers
  • Support for custom adapters
  • Refreshing tokens

Not-yet-planned Features

  • Grant types other than Authorization Code.

Overview

This crate provides two request guards: OAuth2 and TokenResponse. OAuth2 is used to generate redirects to to authentication providers, and TokenResponse is employed on the application’s Redirect URI route to complete the token exchange.

The Adapter trait defines how the temporary code from the authorization server is exchanged for an authentication token. rocket_oauth2 currently provides only one Adapter, using hyper-rustls.

If necessary a custom Adapter can be used, for example to work around a noncompliant authorization server.

Usage

Configure your OAuth client settings in Rocket.toml:

[default.oauth.github]
provider = "GitHub"
client_id = "..."
client_secret = "..."
redirect_uri = "http://localhost:8000/auth/github"

You can also use the ROCKET_OAUTH environment variable; see examples/user_info_custom_provider/run_with_env_var.sh for an example.

Implement routes for a login URI and a redirect URI. Mount these routes and attach the OAuth2 Fairing:

use rocket_oauth2::{OAuth2, TokenResponse};

// This struct will only be used as a type-level key. Multiple
// instances of OAuth2 can be used in the same application by
// using different key types.
struct GitHub;

// This route calls `get_redirect`, which sets up a token request and
// returns a `Redirect` to the authorization endpoint.
#[get("/login/github")]
fn github_login(oauth2: OAuth2<GitHub>, cookies: &CookieJar<'_>) -> Redirect {
    // We want the "user:read" scope. For some providers, scopes may be
    // pre-selected or restricted during application registration. We could
    // use `&[]` instead to not request any scopes, but usually scopes
    // should be requested during registation, in the redirect, or both.
    oauth2.get_redirect(cookies, &["user:read"]).unwrap()
}

// This route, mounted at the application's Redirect URI, uses the
// `TokenResponse` request guard to complete the token exchange and obtain
// the token.
#[get("/auth/github")]
fn github_callback(token: TokenResponse<GitHub>, cookies: &CookieJar<'_>) -> Redirect
{
    // Set a private cookie with the access token
    cookies.add_private(
        Cookie::build(("token", token.access_token().to_string()))
            .same_site(SameSite::Lax)
            .build()
    );
    Redirect::to("/")
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![github_callback, github_login])
        // The string "github" here matches [default.oauth.github] in `Rocket.toml`
        .attach(OAuth2::<GitHub>::fairing("github"))
}

Provider selection

Providers can be specified as a known provider name (case-insensitive). The known provider names are listed as associated constants on the StaticProvider type.

[default.oauth.github]
# Using a known provider name
provider = "GitHub"
client_id = "..."
client_secret = "..."
redirect_uri = "http://localhost:8000/auth/github"

The provider can also be specified with auth_uri and token_uri values:

[default.oauth.custom]
auth_uri = "https://example.com/oauth/authorize"
token_uri = "https://example.com/oauth/token"
client_id = "..."
client_secret = "..."
redirect_uri = "http://localhost:8000/auth/custom"

Modules

  • Constants for commonly used header and parameter names and values.

Structs

  • Represents an error during authorization. Error has a kind and a source which describe the error.
  • The default Adapter implementation. Uses hyper and rustls to perform the token exchange.
  • Utilities for OAuth authentication in Rocket applications.
  • Holds configuration for an OAuth application. This consists of the Provider details, a client_id and client_secret, and an optional redirect_uri.
  • A StaticProvider contains authorization and token exchange URIs known in advance, either at compile-time or early in initialization.
  • The server’s response to a successful token exchange, defined in in RFC 6749 §5.1.

Enums

  • Represents any kind of error that can occur during authorization. Most of these errors are returned by an Adapter.
  • The token types which can be exchanged with the token endpoint

Traits

  • An OAuth2 Adapater can be implemented by any type that facilitates the Authorization Code Grant as described in RFC 6749 §4.1. The implementing type must be able to generate an authorization URI and perform the token exchange.
  • A Provider can retrieve authorization and token exchange URIs specific to an OAuth service provider.