# More Identity Providers

Source: https://keyringauth.com/docs/0.x/rust/sso-providers

## Introduction

[Single Sign-On](https://keyringauth.com/docs/0.x/rust/sso) covers Google, Microsoft and GitHub. This page covers the rest. Most providers speak OpenID Connect, so they need only `SsoProvider::oidc()` and a few fields. A provider that only speaks OAuth 2.0 needs a small driver of your own, built on `OAuth2`, as Keyring's GitHub driver is.

What each provider needs registered with it, its issuer and its freshness are the same as in the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers), which say what was checked and when. The PHP examples run in the PHP package's test suite. The Rust ones on this page are translations, apart from the Discord driver's shape, which the crate's own tests use: check them against your provider before relying on them.

| Provider | How | `freshness` |
|---|---|---|
| [GitLab](https://keyringauth.com/docs/0.x/rust/sso-providers#gitlab) | `oidc` | `Never` |
| [Slack](https://keyringauth.com/docs/0.x/rust/sso-providers#slack) | `oidc` | `Never` |
| [Twitch](https://keyringauth.com/docs/0.x/rust/sso-providers#twitch) | `oidc` | `Never` |
| [Okta](https://keyringauth.com/docs/0.x/rust/sso-providers#okta) | `oidc` | `Reauthenticate` (the default) |
| [Auth0](https://keyringauth.com/docs/0.x/rust/sso-providers#auth0) | `oidc` | `Reauthenticate` (the default) |
| [Keycloak](https://keyringauth.com/docs/0.x/rust/sso-providers#keycloak) | `oidc` | `Reauthenticate` (the default) |
| [Amazon Cognito](https://keyringauth.com/docs/0.x/rust/sso-providers#amazon-cognito) | `oidc` | `Reauthenticate` with managed login, `Never` with the classic hosted UI |
| [Salesforce](https://keyringauth.com/docs/0.x/rust/sso-providers#salesforce) | `oidc` | `Never` |
| [Discord](https://keyringauth.com/docs/0.x/rust/sso-providers#discord), [Bitbucket](https://keyringauth.com/docs/0.x/rust/sso-providers#bitbucket), [Facebook](https://keyringauth.com/docs/0.x/rust/sso-providers#facebook), [LinkedIn](https://keyringauth.com/docs/0.x/rust/sso-providers#linkedin) | a driver | `Never` (the default for `IdentityProvider`) |
| [Apple](https://keyringauth.com/docs/0.x/rust/sso-providers#sign-in-with-apple) | not supported | |

## Picking a Freshness

A provider's [`freshness`](https://keyringauth.com/docs/0.x/rust/sso#freshness) says how much a sign in or confirm through it counts toward a fresh verification. `SsoProvider::oidc()` defaults to `Reauthenticate`, which only works with a provider that sends `auth_time` and makes the user sign in again when asked. The [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#picking-a-freshness) explain how to choose, and how to check the choice, and hold here. A provider that doesn't do both should use `freshness: Some(SsoFreshness::Never)`.

## OpenID Connect Providers

Every provider here takes the [callback URL](https://keyringauth.com/docs/0.x/rust/sso#the-callback-url), `https://example.com/auth/{name}/callback`. Keyring asks for `openid`, `email` and `profile` unless `scopes` says otherwise, and always adds `openid`. The issuer has to match the discovery document exactly, trailing slash included. Keyring requires every ID token to carry the `nonce` it sent.

### GitLab

Add an application in GitLab's settings, with the callback URL as its redirect URI, kept **Confidential**, with the `openid`, `profile` and `email` scopes:

```rust
use laravel_keyring::sso::{SsoFreshness, SsoProvider};

SsoProvider {
    label: Some("GitLab".into()),
    freshness: Some(SsoFreshness::Never),
    ..SsoProvider::oidc(
        "gitlab",
        "https://gitlab.com",
        env.get::<String>("GITLAB_CLIENT_ID").unwrap_or_default(),
        env.get::<String>("GITLAB_CLIENT_SECRET"),
    )
}
```

For a self-managed instance, the issuer is the instance's URL. Keep `Never`: GitLab's `auth_time` is when the user last signed in on any device. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#gitlab).

### Slack

The same shape, with the issuer `https://slack.com` and `Never`. Slack's settings and scopes are in the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#slack).

### Twitch

The same shape, with the issuer `https://id.twitch.tv/oauth2` and `Never`. Twitch's claims and scopes are in the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#twitch).

### Okta

The same shape, with your Okta issuer, such as `https://example.okta.com` or an authorization server's issuer, and the default `Reauthenticate`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#okta) for the issuer to pick, and the note on brokers in [Picking a Freshness](https://keyringauth.com/docs/0.x/rust/sso-providers#picking-a-freshness).

### Auth0

The same shape, with your tenant's issuer, such as `https://example.us.auth0.com/` with its trailing slash, and the default `Reauthenticate`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#auth0).

### Keycloak

The same shape, with the realm's issuer, such as `https://keycloak.example.com/realms/acme`, and the default `Reauthenticate`. A Keycloak on this machine may use plain HTTP, such as one in Docker on `http://localhost:8080`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#keycloak).

### Amazon Cognito

The same shape, with the user pool's issuer, `https://cognito-idp.{region}.amazonaws.com/{pool-id}`: `Reauthenticate` with managed login, `Never` with the classic hosted UI. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#amazon-cognito).

### Salesforce

The same shape, with `https://login.salesforce.com` (or your My Domain) as the issuer and `Never`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#salesforce).

## OAuth 2.0 Providers

A provider without OpenID Connect has no ID token, so a driver reads who signed in from the provider's API with the access token, as Keyring's GitHub driver does. `OAuth2` handles the state, PKCE, the code exchange and client authentication. The driver supplies the endpoints and scopes, and turns the tokens into an `Identity`. Its freshness is `Never` unless the config says otherwise, since `IdentityProvider`'s defaults say it can't be asked for a new sign in.

Each driver keeps the account's permanent ID as the subject, never a username or an address, and sets `email_verified` only when the provider's API says the address is verified.

### Registering a Driver

Register the driver with `sso.extend()`, then configure a provider with it:

```rust
use laravel_keyring::KeyringConfig;
use laravel_keyring::sso::SsoProvider;

laravel::Application::configure().with_config(|config, env| {
    let sso = &mut config.section_mut::<KeyringConfig>().sso;

    sso.extend("discord", Discord::new);
    sso.providers.push(SsoProvider::custom(
        "discord",
        "discord",
        env.get::<String>("DISCORD_CLIENT_ID").unwrap_or_default(),
        env.get::<String>("DISCORD_CLIENT_SECRET"),
    ));
});
```

`label`, `scopes`, `parameters`, `freshness` and `token_endpoint_auth_method` work with an OAuth 2.0 driver, as do `client_id` and `client_secret`. `issuer`, `tenant` and `private_endpoints` belong to the OpenID Connect and Microsoft drivers. The issuer is a constant of the driver: never change it once users have linked accounts, since a link is the pair of the issuer and the subject.

### Discord

In the Discord developer portal, open the application, and add the callback URL as a redirect under **OAuth2**:

```rust
use laravel_keyring::sso::{
    self, AuthorizationRequest, Identity, IdentityProvider, OAuth2, SsoFailed, SsoFailure,
    SsoProvider,
};
use serde_json::{Map, Value};

pub struct Discord {
    oauth: OAuth2,
}

impl Discord {
    pub fn new(provider: &SsoProvider) -> laravel::Result<Self> {
        Ok(Self {
            oauth: OAuth2::new(provider)?
                .default_scopes(["identify", "email"])
                .default_label("Discord"),
        })
    }
}

impl IdentityProvider for Discord {
    fn name(&self) -> &str {
        self.oauth.name()
    }

    fn label(&self) -> String {
        self.oauth.label()
    }

    async fn authorization_url(&self, request: &AuthorizationRequest) -> laravel::Result<String> {
        Ok(self.oauth.authorization_url(
            "https://discord.com/oauth2/authorize",
            self.oauth.authorization_parameters(request),
        ))
    }

    async fn identify(
        &self,
        request: &AuthorizationRequest,
        query: &Map<String, Value>,
    ) -> laravel::Result<Identity> {
        // Checks the callback, then exchanges its code with PKCE.
        let tokens = self
            .oauth
            .tokens("https://discord.com/api/oauth2/token", request, query)
            .await?;

        let user = self
            .oauth
            .read_api(
                sso::http()
                    .get("https://discord.com/api/v10/users/@me")
                    .token(tokens.access_token()),
                "/users/@me",
            )
            .await?;

        // The permanent ID, never the username.
        let Some(id) = user.get("id").and_then(Value::as_str) else {
            return Err(SsoFailed::because(SsoFailure::Unavailable, "Discord named no account.").into());
        };
        let email = user.get("email").and_then(Value::as_str).map(str::to_owned);

        Ok(Identity {
            // "verified", whether Discord has verified it, and only the boolean.
            email_verified: email.is_some() && user.get("verified") == Some(&Value::Bool(true)),
            email,
            ..Identity::new(request, self.name(), "https://discord.com", id)
        })
    }
}
```

`read_api()` turns a failed request, an error status or an answer that isn't JSON into `SsoFailure::Unavailable`, naming only what you pass it, so keep the token out of that.

### Bitbucket

There's no Rust driver written for Bitbucket yet. Build one as Discord's is, with the endpoints, scopes and fields the [PHP driver](https://keyringauth.com/docs/0.x/sso-providers#bitbucket) uses: its subject is the account's `uuid`, and its addresses come from a second API call.

### Facebook

There's no Rust driver written for Facebook yet. Build one as Discord's is, with the endpoints and fields the [PHP driver](https://keyringauth.com/docs/0.x/sso-providers#facebook) uses. Facebook never says whether an address is verified, so `email_verified` is always `false`.

### LinkedIn

There's no Rust driver written for LinkedIn yet. LinkedIn's OpenID Connect tokens don't carry the `nonce` Keyring requires, so the [PHP driver](https://keyringauth.com/docs/0.x/sso-providers#linkedin) is an OAuth 2.0 driver that reads the userinfo endpoint. Build one as Discord's is, from what the PHP driver reads.

### Writing Your Own

Any other OAuth 2.0 provider follows the Discord driver's shape. The [PHP checklist](https://keyringauth.com/docs/0.x/sso-providers#writing-your-own) holds, in Rust terms:

1. Pass the provider's endpoints to `authorization_url()` and `tokens()`, and its scopes and label to `default_scopes()` and `default_label()`.
2. For a provider that only takes the secret in the form, set `token_endpoint_auth_method` to `client_secret_post`. To accept another method, list it with `with_auth_methods()` and call `exchange_with()` yourself.
3. Read the user with `read_api()` and `sso::http()`, which has short timeouts and follows no redirects. Turn any other failure into `SsoFailed::because(SsoFailure::Unavailable, ...)`, without the token in the message.
4. Use the account's permanent ID as the `subject`: one that never changes and is never reused.
5. Pick one issuer for the provider, such as its website, and never change it.
6. Set `email_verified` to `true` only when the provider's API says the address is verified, as a boolean.
7. Leave `freshness()` and `supports_reauthentication()` at their defaults.
8. A refused code answered with a `200` and an `error` in the body is already read as a failed exchange by `OAuth2`.
9. Test it with laravel-rust's HTTP client fake, answering the token endpoint and the API with the bodies from the provider's docs.

`OAuth2` only reads the callback from the query string, so the provider has to send the user back with a `GET`.

## Not Supported

### Sign in with Apple

Not supported, for the reasons the [PHP docs](https://keyringauth.com/docs/0.x/sso-providers#sign-in-with-apple) give: Apple sends the user back with a cross-site `POST` when it's asked for the name or email, which the `SameSite=Lax` session cookie doesn't come with, and its client secret is a JWT your server has to sign and refresh.
