Skip to main content

Crate simple_oauth

Crate simple_oauth 

Source
Expand description

§simple-oauth

Simple server-side OAuth2 login and authorization with the Authorization Code Flow, including common OAuth providers. Built on top of oauth2 and reqwest.

§Example

use simple_oauth::SimpleOAuthClient;

async fn example() {
    let oauth_client = SimpleOAuthClient::builder()
        .provider(simple_oauth::common::GitHub)
        .credentials(("client-id", "client-secret"))
        .redirect_url("https://myserver/auth/github/callback")
        .build()
        .unwrap();

    // Build the authorization URL to redirect the user
    let auth_url = oauth_client
        .authorize_url()
        .scopes(&["read:user", "user:email"])
        .build()
        .unwrap();

    // Save the state and PKCE verifier in cache/session
    let initial_state = auth_url.state;
    let pkce_verifier = auth_url.pkce_verifier;

    // In the callback route, extract the `code` and `state` query parameters
    let code = "returned_code";
    let state = "returned_state";

    // Perform token exchange
    let token = oauth_client
        .exchange_code()
        .code(code)
        .pkce_verifier(pkce_verifier)
        .build()
        .await
        .unwrap();
    let _access_token = &token.access_token;
    let _id_token = token.id_token.as_deref();

    // Get basic user info
    let user = oauth_client.get_user_info(&token.access_token).await.unwrap();
    let _id = user.id;
    let _name = user.name;
}

§Custom providers

If you only need authorization and token exchange, implement SimpleOAuthProvider:

#[derive(Debug, Clone)]
struct MyProvider;

impl simple_oauth::SimpleOAuthProvider for MyProvider {
    fn authorize_url(&self) -> &str {
        "https://provider.example/oauth/authorize"
    }

    fn token_url(&self) -> &str {
        "https://provider.example/oauth/token"
    }

    fn default_scopes(&self) -> &'static [&'static str] {
        &["profile"]
    }
}

Providers that support normalized profile lookup can also implement UserInfoProvider, which enables SimpleOAuthClient::get_user_info.

Modules§

common
Common OAuth providers
types

Structs§

SimpleOAuthClient
SimpleOAuthClientAuthorizeUrlBuilder
Use builder syntax to set the inputs and finish with build().
SimpleOAuthClientBuilder
Use builder syntax to set the inputs and finish with build().
SimpleOAuthClientExchangeCodeBuilder
Use builder syntax to set the inputs and finish with build().
SimpleOAuthClientExchangeRefreshTokenBuilder
Use builder syntax to set the inputs and finish with build().

Enums§

SimpleOAuthError

Traits§

SimpleOAuthProvider
Trait for all OAuth providers
UserInfoProvider
Trait for OAuth providers that support fetching normalized user info.