[][src]Crate yup_oauth2

This library can be used to acquire oauth2.0 authentication for services.

For your application to use this library, you will have to obtain an application id and secret by following this guide (for Google services) respectively the documentation of the API provider you want to connect to.

Device Flow Usage

As the DeviceFlow involves polling, the DeviceFlowHelper should be used as means to adhere to the protocol, and remain resilient to all kinds of errors that can occur on the way.

Service account "flow"

When using service account credentials, no user interaction is required. The access token can be obtained automatically using the private key of the client (which you can download from the API provider). See examples/service_account/ for an example on how to use service account credentials. See developers.google.com for a detailed description of the protocol. This crate implements OAuth for Service Accounts based on the Google APIs; it may or may not work with other providers.

Installed Flow Usage

The InstalledFlow involves showing a URL to the user (or opening it in a browser) and then either prompting the user to enter a displayed code, or make the authorizing website redirect to a web server spun up by this library and running on localhost.

In order to use the interactive method, use the InstalledInteractive FlowType; for the redirect method, use InstalledRedirect, with the port number to let the server listen on.

You can implement your own AuthenticatorDelegate in order to customize the flow; the InstalledFlow uses the present_user_url method.

The returned Token is stored permanently in the given token storage in order to authorize future API requests to the same scopes.

The following example, which is derived from the (actual and runnable) example in examples/test-installed/, shows the basics of using this crate:

use futures::prelude::*;
use yup_oauth2::GetToken;
use yup_oauth2::{Authenticator, InstalledFlow};

use hyper::client::Client;
use hyper_rustls::HttpsConnector;

use std::path::Path;

fn main() {
    // Boilerplate: Set up hyper HTTP client and TLS.
    let https = HttpsConnector::new(1);
    let client = Client::builder()
        .keep_alive(false)
        .build::<_, hyper::Body>(https);

    // Read application secret from a file. Sometimes it's easier to compile it directly into
    // the binary. The clientsecret file contains JSON like `{"installed":{"client_id": ... }}`
    let secret = yup_oauth2::read_application_secret(Path::new("clientsecret.json"))
        .expect("clientsecret.json");

    // There are two types of delegates; FlowDelegate and AuthenticatorDelegate. See the
    // respective documentation; all you need to know here is that they determine how the user
    // is asked to visit the OAuth flow URL or how to read back the provided code.
    let ad = yup_oauth2::DefaultFlowDelegate;

    // InstalledFlow handles OAuth flows of that type. They are usually the ones where a user
    // grants access to their personal account (think Google Drive, Github API, etc.).
    let inf = InstalledFlow::new(
        client.clone(),
        ad,
        secret,
        yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect(8081),
    );
    // You could already use InstalledFlow by itself, but usually you want to cache tokens and
    // refresh them, rather than ask the user every time to log in again. Authenticator wraps
    // other flows and handles these.
    // This type of authenticator caches tokens in a JSON file on disk.
    let mut auth = Authenticator::new_disk(
        client,
        inf,
        yup_oauth2::DefaultAuthenticatorDelegate,
        "tokencache.json",
    )
    .unwrap();
    let s = "https://www.googleapis.com/auth/drive.file".to_string();
    let scopes = vec![s];

    // token(<scopes>) is the one important function of this crate; it does everything to
    // obtain a token that can be sent e.g. as Bearer token.
    let tok = auth.token(scopes);
    // Finally we print the token.
    let fut = tok.map_err(|e| println!("error: {:?}", e)).and_then(|t| {
        println!("The token is {:?}", t);
        Ok(())
    });

    tokio::run(fut)
}

Structs

ApplicationSecret

Represents either 'installed' or 'web' applications in a json secrets file. See ConsoleApplicationSecret for more information

Authenticator

Authenticator abstracts different GetToken implementations behind one type and handles caching received tokens. It's important to use it (instead of the flows directly) because otherwise the user needs to be asked for new authorization every time a token is generated.

ConsoleApplicationSecret

A type to facilitate reading and writing the json secret file as returned by the google developer console

DefaultAuthenticatorDelegate

Uses all default implementations by AuthenticatorDelegate, and makes the trait's implementation usable in the first place.

DefaultFlowDelegate

Uses all default implementations in the FlowDelegate trait.

DeviceFlow

Implements the Oauth2 Device Flow It operates in two steps:

DiskTokenStorage

Serializes tokens to a JSON file on disk.

InstalledFlow

InstalledFlow provides tokens for services that follow the "Installed" OAuth flow. (See https://www.oauth.com/oauth2-servers/authorization/, https://developers.google.com/identity/protocols/OAuth2InstalledApp). You should use it wrapped inside an Authenticator to benefit from refreshing tokens and caching previously obtained authorization.

MemoryStorage

A storage that remembers values for one session only.

NullStorage

A storage that remembers nothing.

PollInformation

Contains state of pending authentication requests

Scheme

A scheme for use in hyper::header::Authorization

ServiceAccountAccess

A token source (GetToken) yielding OAuth tokens for services that use ServiceAccount authorization. This token source caches token and automatically renews expired ones, meaning you do not need (and you also should not) use this with Authenticator. Just use it directly.

ServiceAccountKey

JSON schema of secret service account key. You can obtain the key from the Cloud Console at https://console.cloud.google.com/.

Token

Represents a token as returned by OAuth2 servers.

Enums

FlowType

All known authentication types, for suitable constants

InstalledFlowReturnMethod

cf. https://developers.google.com/identity/protocols/OAuth2InstalledApp#choosingredirecturi

PollError

Encapsulates all possible results of a poll_token(...) operation in the Device flow.

RefreshResult

All possible outcomes of the refresh flow

RequestError

Encapsulates all possible results of the token(...) operation

TokenType

Represents all implemented token types

Constants

GOOGLE_DEVICE_CODE_URL

Traits

AuthenticatorDelegate

A partially implemented trait to interact with the Authenticator

FlowDelegate

FlowDelegate methods are called when an OAuth flow needs to ask the application what to do in certain cases.

GetToken

A provider for authorization tokens, yielding tokens valid for a given scope. The api_key() method is an alternative in case there are no scopes or if no user is involved.

TokenStorage

Implements a specialized storage to set and retrieve Token instances. The scope_hash represents the signature of the scopes for which the given token should be stored or retrieved. For completeness, the underlying, sorted scopes are provided as well. They might be useful for presentation to the user.

Functions

parse_application_secret

Read an application secret from a JSON string.

read_application_secret

Read an application secret from a file.

service_account_key_from_file

Read a service account key from a JSON file. You can download the JSON keys from the Google Cloud Console or the respective console of your service provider.