simple-oauth 0.1.0-beta.3

Simple OAuth2 login and authorization
Documentation

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.