# Single Sign-On

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

## Introduction

Single sign-on lets users sign in with Google, Microsoft, GitHub, or any OpenID Connect provider, as in the PHP package. A sign in goes through the same [pipeline](https://keyringauth.com/docs/0.x/rust/sign-in-flow#the-verification-pipeline) as the login form, so rate limits, your policy and risk checks all apply, and a user with a second factor is still asked for it. Accounts are matched by the issuer and subject the provider vouches for, never by email address, and stored as the PHP package stores them, so a link either side made signs in on the other.

## Setting Up

Turn on `features.sso` and list the providers in `sso.providers`, built with `SsoProvider::oidc`, `google`, `microsoft` or `github`:

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

laravel::Application::configure()
    .with_config(|config, env| {
        let keyring = config.section_mut::<KeyringConfig>();
        keyring.features.sso = true;
        // Linking, with the other sign-in methods.
        keyring.features.manage_authenticators = true;
        keyring.sso.providers = vec![
            SsoProvider::google(
                "google",
                env.get::<String>("GOOGLE_CLIENT_ID").unwrap_or_default(),
                env.get::<String>("GOOGLE_CLIENT_SECRET"),
            ),
            SsoProvider {
                label: Some("Okta".into()),
                freshness: Some(SsoFreshness::RoundTrip),
                ..SsoProvider::oidc(
                    "okta",
                    "https://example.okta.com",
                    env.get::<String>("OKTA_CLIENT_ID").unwrap_or_default(),
                    env.get::<String>("OKTA_CLIENT_SECRET"),
                )
            },
        ];
    });
```

There's no factor to register: `features.sso` with at least one provider is the PHP package's `SingleSignOn` in `Keyring::factors()`. [More Identity Providers](https://keyringauth.com/docs/0.x/rust/sso-providers) has settings for other providers, and drivers of your own.

### The Callback URL

Every provider sends the user back to the same URL, whether they're signing in, linking or confirming: `/auth/{name}/callback` on `APP_URL`, such as `https://example.com/auth/google/callback`, whatever host a request names. It starts at the provider's `link_root_using()` when you set one, followed by Keyring's `prefix`. Register it exactly as written, and add your local one too, such as `http://localhost:8000/auth/google/callback`.

| Method | URI | Does |
|---|---|---|
| `GET` | `/auth/{provider}/redirect` | Sends a guest to the provider, under the `keyring-login-options` limiter. |
| `GET` | `/auth/{provider}/callback` | Where the provider sends the user back, to sign in, link or confirm. |
| `GET` | `/confirm/sso/redirect` | Sends a signed-in user to the provider of a link on the confirm page. See [Step-Up](https://keyringauth.com/docs/0.x/rust/sso#step-up). |
| `POST` | `/user/authenticators/sso` | Begins a link, with `provider`. See [Linking and Unlinking](https://keyringauth.com/docs/0.x/rust/sso#linking-and-unlinking). |

The routes are only registered while `features.sso` is on and a provider is configured, and answer `404` for a provider that isn't. A request your own code started with [`sso::start()`](https://keyringauth.com/docs/0.x/rust/sso#signing-up-with-a-provider) for another purpose is spent at Keyring's callback and answered with a `404`.

### Google

Create a "Web application" OAuth client ID in the Google Cloud console, with the callback URL as a redirect URI, and use `SsoProvider::google()`, as above. The scopes, `hd` claim and freshness are the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/sso#google) describe: freshness is `never` by default, and `reauthenticate` only once your app has Google's session age claims.

### Microsoft

Register an application in the Microsoft Entra admin center, with the callback URL as a "Web" redirect URI, and a client secret:

```rust
SsoProvider::microsoft(
    "microsoft",
    env.get::<String>("MICROSOFT_TENANT"),
    env.get::<String>("MICROSOFT_CLIENT_ID").unwrap_or_default(),
    env.get::<String>("MICROSOFT_CLIENT_SECRET"),
)
```

The `tenant` is `None` for `common`, or `organizations`, `consumers`, or a tenant ID or domain, as the [PHP docs](https://keyringauth.com/docs/0.x/sso#microsoft) describe. Freshness is `reauthenticate`, which needs the `auth_time` optional claim on the app registration. Microsoft's `email` is only verified with the `xms_edov` claim.

### GitHub

Create an OAuth app in GitHub's developer settings, with the callback URL as its "Authorization callback URL", and use `SsoProvider::github()`. Keyring reads who signed in from GitHub's API: the numeric ID, and the primary address when `user:email` was granted, verified as GitHub says. GitHub can't be asked for a new sign in, so its freshness is `never`, and `reauthenticate` is refused.

### Any OpenID Connect Provider

Any provider with a discovery document works with `SsoProvider::oidc()`, given the issuer. The issuer must match the discovery document exactly, and the issuer and every endpoint must be HTTPS, except on this machine. Keyring refuses a token endpoint or key set on a private, local or reserved address, IPv4-mapped, -compatible and -translated IPv6 included, unless it's on the issuer's own host and port, or `private_endpoints` is on. The `oidc` driver defaults to `reauthenticate`. See the [PHP docs](https://keyringauth.com/docs/0.x/sso#any-openid-connect-provider).

## Configuration

| Setting | Default | Notes |
|---|---|---|
| `sso.providers` | Empty | The providers, in the order the login page lists them. |
| `sso.request_for` | 10 minutes | How long a user sent to a provider has to come back. Each browser keeps up to five at once. |
| `sso.cache_for` | One hour | How long discovery documents and signing keys are cached. A key ID the cache doesn't know reads the keys again at most once a minute. |
| `sso.store` | The default store | The cache store for them. |

Each `SsoProvider` has the PHP package's options as fields:

| Field | |
|---|---|
| `name` | The key, as the routes name it. |
| `driver` | `Driver::Oidc`, `Google`, `Microsoft`, `GitHub` or `Custom(name)`, set by the constructor. |
| `client_id`, `client_secret` | `client_secret` is `None` for a public client. Every request uses PKCE either way. |
| `issuer` | The `oidc` driver's issuer. |
| `tenant` | The `microsoft` driver's tenant. `None` is `common`. |
| `label` | The button's text, the PHP package's `name`. |
| `scopes` | Replaces the driver's scopes. |
| `parameters` | More to send the user with, as `(name, value)` pairs, such as `("prompt".into(), "select_account".into())`. |
| `freshness` | `Some(SsoFreshness::Reauthenticate)`, `RoundTrip` or `Never`, or `None` for the driver's own. |
| `token_endpoint_auth_method` | `client_secret_basic`, `client_secret_post` or `none`. |
| `private_endpoints` | Lets an OpenID Connect provider's endpoints be on a private address. Only for an issuer you run or trust. |
| `options` | Anything else a driver of your own reads. |

A provider is checked when a request builds it, as the PHP package's drivers are: one that can't work, an empty `client_id` say, fails its routes with a server error and is left off the login page.

### Freshness

Each provider's `freshness` says how much a sign in counts toward a [fresh verification](https://keyringauth.com/docs/0.x/rust/step-up#fresh-verification), exactly as in the PHP package:

| `freshness` | A sign in counts as fresh | A confirm |
|---|---|---|
| `Reauthenticate` | From when the provider says the user signed in (`auth_time`). Never without one. | Asks the provider for a new sign in, with `max_age=0` and `prompt=login`. |
| `RoundTrip` | From when the user comes back. | A plain round trip. |
| `Never` | Never. | A plain round trip that counts toward the session's level, never as fresh. |

The defaults are the PHP package's: `reauthenticate` for `oidc` and `microsoft`, `never` for `google` and `github`. The config's `freshness` wins over the driver's, and `reauthenticate` for a provider that can't reauthenticate is refused. `sso::freshness(name)` gives the value that counts. There's no `false` for `never`.

> [!WARNING]
> `RoundTrip` lets anyone at a browser still signed in to the provider get a fresh verification without typing anything. Opt in only where you accept that.

## Login Buttons

The `login` page gets a `providers` prop, with each provider's `name`, `label` and `url`, leaving out one that can't be built. A plain link works best, and an Inertia visit gets a `409` with `X-Inertia-Location`. Add `?remember=1` for "remember me", which Keyring keeps for the callback.

For your own pages, `laravel_keyring::sso::providers()` returns the configured providers, each a `ConfiguredProvider` with its name, label, freshness and whether it can reauthenticate, and `sso::names()` returns the names alone. Failures go back to the login page as in the PHP package: an account nobody linked gets the wrong-password message, a failed check gets "We couldn't sign you in", and a user who said no gets `sso-cancelled`.

## Linking and Unlinking

Users link accounts from your settings page, with `features.manage_authenticators` on. A link is an enrollment like any other sign-in method's: it needs a fresh verification, and the password when the account has one and no established second factor. `POST /user/authenticators/sso` `{ "provider", "password" }` answers `enrollment-started` with `{ "enrollment": { "provider", "url" } }`, and the provider's callback finishes it, answering `authenticator-added`, or `authenticator-updated` for an account the user had already linked, or a `422` on `provider` for one someone else has. The browser package's `linkProvider()` does both steps. What the [PHP docs](https://keyringauth.com/docs/0.x/sso#linking-and-unlinking) say about the answers, unlinking and the freeze holds here.

`laravel_keyring::sign_in_methods(&user)` lists the user's links, each with `provider` and `email`. Unlink with `DELETE /user/authenticators/{authenticator}`.

## How It Fits With the Rest

### Second Factors and Policies

As in the PHP package: a sign in with a provider is one knowledge proof, like a password. A link is never a second factor, never the default, never offered on the challenge page, and never comes with recovery codes. A provider's `amr` and `acr` are kept on the [`Verification`](https://keyringauth.com/docs/0.x/rust/step-up#verification-properties) as `provider_amr` and `provider_acr`, and never count toward the level.

### Hearing About Accepted Identities

`laravel_keyring::events::ProviderIdentityAccepted` fires each time a provider's account is accepted as one of the user's links, for a sign in, a confirm or a link, as in the PHP package. It carries the `Identity` with its request's secrets: `Identity::without_secrets()` gives one without them, for a listener that keeps it.

### Step-Up

A link answers the [confirm page](https://keyringauth.com/docs/0.x/rust/step-up#the-confirm-flow) while its provider is configured, with `challenge` `{ "provider", "label", "url" }`: `GET /confirm/sso/redirect?authenticator=` sends the user back to the provider, with `max_age=0` and `prompt=login` for one that reauthenticates (only `max_age` at Google, only `prompt=login` at Microsoft), and the callback has to bring the link's account with an `auth_time` from no more than a minute before the user was sent there. The rest is the [PHP package's](https://keyringauth.com/docs/0.x/sso#step-up).

### Users Whose Only Way In Is Never Fresh

As in the [PHP docs](https://keyringauth.com/docs/0.x/sso#users-whose-only-way-in-is-never-fresh): a user whose only sign-in method is a link at a `never` provider can sign in but can't pass a fresh verification, so they get `enroll-first` at once. The way out is a password reset. Have a user who [signs up with such a provider](https://keyringauth.com/docs/0.x/rust/sso#signing-up-with-a-provider) set a password or add a passkey while the sign up is still fresh.

### Password Resets and Email Changes

A completed password reset unlinks every identity provider on the account, with `AuthenticatorRemoved` for each, as in the PHP package. An undone email change removes the links added since the change.

### Failures and the Security Log

Failures are logged and dispatched as in the PHP package (`factor_failed`, `second_factor_failed`, `enrollment_refused`), apart from Laravel's `Failed` event, which laravel-rust doesn't have. A failure is an `sso::SsoFailed` inside the error, whose `reason` is an `SsoFailure`. Its message never carries a code, token or secret.

## No Sign Up, and No Linking by Email

As in the PHP package, Keyring never creates an account for someone who signs in with a provider, and never links an account to a user because they share an address. To let people sign up with a provider, build the routes yourself, as below.

### Signing Up With a Provider

`sso::start()` and `sso::complete()` send users to a provider and take them back at routes of your own, as `Keyring::sso()->start()` and `complete()` do. Give the request a purpose other than `login`, `link` or `confirm` (those are refused), build the URL the provider sends users back to with `sso::redirect_uri()`, from `APP_URL` as Keyring's own callback is, never with `laravel::url::to()`, which goes by the request's host, and check the purpose when the identity comes back.

`sso::link_new_account(&user, &identity)` links the provider's account to a user you just created with it, stored under `sso::credential_id()` so Keyring's own button signs them in, and dispatches `AuthenticatorAdded`. The PHP example creates the row itself. It refuses a user who already has any sign-in method, a password included, and an account someone already linked.

`laravel_keyring::sign_in` signs people in from those routes, as `Keyring::attempt()` and `SignIn::as()` do. `sign_in::attempt(&auth, &session, &request, SignInWith::Sso { identity, remember })` signs in whoever linked the account, through Keyring's pipeline. `sign_in::as_user(&auth, &session, &request, &user, &[Verified::authenticator(link)], remember)` signs in a new account with what creating it proved. The PHP example translates like this:

```rust
use laravel::auth::Auth;
use laravel::http::{IntoResponse, Redirect, Request, Response};
use laravel::session::Session;
use laravel::validation::InvalidInput;
use laravel_keyring::http::wants_json;
use laravel_keyring::sign_in::{self, SignInWith, Verified};
use laravel_keyring::sso::{self, SsoFailed, StartOptions};

// GET /sign-up/google, for guests.
async fn sign_up_with_google(session: Session) -> laravel::Result<Response> {
    let url = sso::start(&session, "google", "sign-up", &sso::redirect_uri("/sign-up/google/callback"), StartOptions::default()).await?;

    Ok(Redirect::to(url).into_response())
}

// GET /sign-up/google/callback, for guests. List it in `sessions.block`, as `->block()`.
async fn signed_up_with_google(auth: Auth<User>, session: Session, request: Request) -> laravel::Result<Response> {
    let identity = match sso::complete(&session, &request, "google").await {
        Ok(identity) => identity,
        Err(error) if error.downcast_ref::<SsoFailed>().is_some() => {
            let errors = InvalidInput::new().with("email", "We couldn't sign you up with Google.");
            return Ok(Redirect::to("/register").with_errors(&errors).into_response());
        }
        Err(error) => return Err(error),
    };

    if identity.request.purpose != "sign-up" {
        return Err(laravel::abort(404));
    }

    // Someone who already signed up: an ordinary sign in. A refusal goes to
    // the login page, as Keyring's own callback sends it: back would be
    // Google.
    if sso::linked(&identity).await?.is_some() {
        let signed_in = sign_in::attempt(&auth, &session, &request, SignInWith::Sso { identity, remember: false }).await;

        return to_login(&request, signed_in);
    }

    let email = identity.email.as_deref().map(|email| email.trim().to_lowercase());

    // Google only vouches for who owns a Gmail address, or one in a Google
    // Workspace domain (the "hd" claim). Any other address was verified
    // once, when the Google account was made, and may have changed hands
    // since.
    let workspace = identity.claims.get("hd").and_then(|hd| hd.as_str()).is_some_and(|hd| !hd.is_empty());
    let vouched = identity.email_verified && email.as_deref().is_some_and(|email| email.ends_with("@gmail.com") || workspace);

    let Some(email) = email.filter(|_| vouched) else {
        let errors = InvalidInput::new().with("email", "Sign up with your email address, then link Google from your settings.");
        return Ok(Redirect::to("/register").with_errors(&errors).into_response());
    };

    if address_taken(&email).await? {
        let errors = InvalidInput::new().with("email", "Sign up with your email address, then link Google from your settings.");
        return Ok(Redirect::to("/register").with_errors(&errors).into_response());
    }

    // Your own: a user with this address, verified, and no password.
    let user = create_user_without_password(&identity, &email).await?;
    let link = sso::link_new_account(&user, &identity).await?;

    // The account didn't exist until this request, so this sign in counts
    // as fresh: long enough to choose a password or add a passkey.
    let signed_in = sign_in::as_user(&auth, &session, &request, &user, &[Verified::authenticator(link)], false).await;

    to_login(&request, signed_in.map(|_| Redirect::to("/settings/security").into_response()))
}

// A sign in Keyring refused, as the PHP example catches its
// ValidationException: to the login page with the errors, or the 422 for
// JSON.
fn to_login(request: &Request, answer: laravel::Result<Response>) -> laravel::Result<Response> {
    match answer {
        Err(error) if !wants_json(request) => match error.downcast_ref::<InvalidInput>() {
            Some(errors) => Ok(Redirect::to("/login").with_errors(errors).into_response()),
            None => Err(error),
        },
        answer => answer,
    }
}
```

The [PHP example's notes](https://keyringauth.com/docs/0.x/sso#signing-up-with-a-provider) hold here too. `address_taken()` and `create_user_without_password()` are yours: check the address as registration does, counting `laravel_keyring::address_reserved()` too. The PHP example creates the user and the link in one transaction; here, delete the user you just created if `link_new_account()` fails, so nobody is left with an account they can't sign in to.

Only a new account goes through `as_user()`, which asks neither the policy nor risk, so never call it for an existing one. It takes `Verified::password()` or `Verified::authenticator(id)`, one of the user's own sign-in methods. Put the routes behind laravel-rust's `RedirectIfAuthenticated`, as the PHP example puts them behind `guest`: `attempt()` sends a browser someone is signed in on `home`, and `as_user()` refuses one that's impersonating someone with a `403`.

The PHP example limits its callback with `throttle:keyring-login-options`, as each call may create an account. The crate has no named limiter to give a route of yours, so put a rate limit of your own on the callback with `laravel::rate_limit`. "Remember me" goes in `StartOptions`' `data`, read back from `identity.request.data`, as Keyring's own redirect does with `?remember`. `StartOptions` also takes `max_age` and `login_hint`.

## Frontends Laravel Doesn't Serve

A [headless frontend](https://keyringauth.com/docs/0.x/rust/headless) can offer providers as with the PHP package: a JSON request to the redirect route answers `{ "url" }`, and the browser package's `signInWithProvider()` does both steps. Start the callback URL at the frontend with the provider's `link_root_using()`, and have the frontend pass the callback's path and query to Keyring as JSON. The answers are the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/sso#frontends-laravel-doesnt-serve) list.

## Security Notes

The PHP package's [notes](https://keyringauth.com/docs/0.x/sso#security-notes) hold: `private_endpoints` is only for an issuer you run or trust, keep `SESSION_SAME_SITE` at `lax`, `reauthenticate` behind a broker only means something when users type their credentials at the broker, Google and Microsoft sign with RS256, and Keyring's session carries on after the provider's ends.

Keyring only fetches HTTPS endpoints, or plain HTTP to an issuer on this machine, never follows a redirect, and gives up after 5 seconds connecting and 10 in all. Host names are resolved through the system's resolver. A token endpoint, key set or userinfo endpoint held to public addresses is looked up once, and the request connects only to the addresses that were checked, so a name can't answer with a public address for the check and a private one for the request (DNS rebinding), which the PHP package can't rule out. A name with a dot that didn't resolve is fetched from nowhere. Behind a proxy (`HTTPS_PROXY`), the proxy looks the name up again for itself, so limit what it can reach from your network. `private_endpoints`, an issuer on this machine and an endpoint on the issuer's own host skip the check, and with it the pinning.

## Custom Drivers

A driver of your own, as `Keyring::sso()->extend()` registers one, implements `sso::IdentityProvider`:

- `name()` returns the name it's configured under, and `label()` the button's text.
- `supports_reauthentication()` and `freshness()` default to `false` and `Never`.
- `authorization_url()` builds the URL from the `AuthorizationRequest` Keyring made and keeps in the session.
- `identify()` turns the callback's query string, as a map, into an `Identity` (`Identity::new(request, name, issuer, subject)`, then whichever of the rest the provider says), or fails with an `SsoFailed`.

Keyring puts the provider's name and the request it took from the session on the identity, whatever the driver says, and refuses one with no issuer or subject. Register it with `sso.extend()` under a driver name, or under one of Keyring's (`oidc`, `google`, `microsoft`, `github`) to replace that, and configure providers with `SsoProvider::custom()`. Whatever else it reads goes in the provider's `options`:

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

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"),
));
```

[More Identity Providers](https://keyringauth.com/docs/0.x/rust/sso-providers#discord) has the Discord driver, and a [checklist](https://keyringauth.com/docs/0.x/rust/sso-providers#writing-your-own).

### Building on Keyring's Drivers

Keyring's own drivers are built on pieces in `laravel_keyring::sso` that yours can use too, as the PHP package's are on `OAuth2Provider` and `OidcProvider`. A Rust driver keeps one of them rather than extending a class.

For an OAuth 2.0 provider without OpenID Connect, keep an `OAuth2` and implement `IdentityProvider` with it, as the GitHub driver does. `OAuth2::new()` checks the provider's entry as `OAuth2Provider`'s constructor does (`with_auth_methods()` stands in for `allowedAuthMethods()`), and `default_scopes()` and `default_label()` for `defaultScopes()` and `defaultLabel()`. It handles the state, PKCE, the code exchange and client authentication: `authorization_parameters()` and `authorization_url()` build where to send the user, and `tokens()` checks the callback (`check_callback()`), takes its `code()` and exchanges it (`exchange()`). You pass it the endpoints and read who signed in, usually with `read_api()` and `sso::http()`, Keyring's client, which has short timeouts and follows no redirects.

For an OpenID Connect provider, keep an `Oidc` and implement `OpenIdConnect`. `Oidc::new()` checks the entry as `OidcProvider`'s constructor does, and on its own it's the `oidc` driver, with `default_scopes()`, `default_label()` and `default_freshness()`. `OpenIdConnect`'s methods are `OidcProvider`'s override points, each doing what Keyring does unless you say otherwise: `trusts_discovered_issuer()`, `accepts_issuer_parameter()`, `accepted_issuer()`, `trusts_key()`, `takes_claims_parameter()`, `reauthentication_parameters()`, `auth_method()`, `email_verified()` and `identity_from()`. Anything that implements it is an `IdentityProvider`. Where a PHP override calls `parent::`, call Keyring's step in `sso::oidc` (`oidc::identity_from()`, `oidc::verify()`, `oidc::authorization_url()` and the rest).

`Google`, `Microsoft` and `GitHub` are public too, so the PHP docs' Workspace driver builds on Google's, passing on each hook Google changes:

```rust
use laravel_keyring::KeyringConfig;
use laravel_keyring::sso::{
    AuthorizationRequest, Google, Identity, Oidc, OpenIdConnect, SsoFailed, SsoFailure, Tokens,
    oidc,
};
use serde_json::{Map, Value};

struct Workspace {
    google: Google,
    domain: String,
}

impl OpenIdConnect for Workspace {
    fn oidc(&self) -> &Oidc {
        self.google.oidc()
    }

    // What Google changes, passed on.
    fn accepted_issuer(&self, claims: &Map<String, Value>, discovered: &str) -> Option<String> {
        self.google.accepted_issuer(claims, discovered)
    }

    fn takes_claims_parameter(&self, discovery: &Map<String, Value>) -> bool {
        self.google.takes_claims_parameter(discovery)
    }

    fn reauthentication_parameters(&self, max_age: i64) -> Vec<(String, String)> {
        self.google.reauthentication_parameters(max_age)
    }

    async fn identity_from(
        &self,
        request: &AuthorizationRequest,
        tokens: &Tokens,
        query: &Map<String, Value>,
    ) -> laravel::Result<Identity> {
        // parent::identityFrom(): the ID token, once it's passed every check.
        let identity = oidc::identity_from(self, request, tokens, query).await?;

        if identity.claims.get("hd").and_then(Value::as_str) != Some(self.domain.as_str()) {
            return Err(SsoFailed::because(
                SsoFailure::InvalidToken,
                format!("[{}] signed in an account outside the workspace.", self.oidc().name()),
            )
            .into());
        }

        Ok(identity)
    }
}

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

    sso.extend("workspace", |provider| {
        Ok(Workspace {
            google: Google::new(provider)?,
            domain: provider.options.get("domain").and_then(Value::as_str).unwrap_or_default().to_owned(),
        })
    });

    // The oidc driver, asking for less.
    sso.extend("okta", |provider| Ok(Oidc::new(provider)?.default_scopes(["openid", "email"])));
});
```

A driver that keeps `Google` or `Microsoft` inherits none of its hooks, where a PHP subclass inherits every override: each one you don't write is Keyring's default, not that driver's. So pass on every hook the driver changes. For `Google` that's `accepted_issuer()`, `takes_claims_parameter()` and `reauthentication_parameters()`, as above. For `Microsoft` it's `trusts_discovered_issuer()`, `accepts_issuer_parameter()`, `accepted_issuer()`, `trusts_key()`, `reauthentication_parameters()`, `email_verified()` and `identity_from()`.

> [!WARNING]
> Most hooks fail closed when they're forgotten, but two of Microsoft's don't. Without `trusts_key()`, any key Microsoft publishes is believed for any tenant on the `common` and `organizations` endpoints. Without `email_verified()`, Keyring goes by an `email_verified` claim rather than `xms_edov`. Pass on `identity_from()` by calling `oidc::identity_from(self, ...)` and then refusing a request with `max_age` whose token has no `auth_time`, as Microsoft's does: calling `self.microsoft.identity_from()` checks the token with Microsoft's hooks rather than yours.

The callback's checks, the authorization parameters, the exchange and the private-address guard (`checkCallback()`, `authorizationParameters()`, `exchange()`, `tokens()`, `mayFetch()` and `endpointIn()` in PHP) have no hook: a driver that changes them implements `IdentityProvider` itself, calling the rest of `sso::oidc`'s steps. ID tokens are checked with `oidc::verify()`, as `SignedToken` isn't public. `oidc::userinfo(&driver, access_token, subject)` reads the discovered userinfo endpoint, behind the private-address guard, and refuses an answer about another subject, which the PHP package has no counterpart for. A userinfo answer that's a JWT isn't read. `is_secure()`, `is_local()`, `same_host()` and `is_inward()` are the address checks Keyring makes, for requests your driver makes itself. `is_inward()` only checks: a request your driver then makes looks the name up again, so it isn't held to the addresses checked as Keyring's own are.

## Testing

`laravel_keyring::testing::FakeIdentityProvider`, behind the crate's `testing` feature, stands in for a provider. It answers Keyring's requests through laravel-rust's HTTP client fake: discovery, signing keys, the token endpoint and GitHub's API. Its ID tokens are really signed, so every check Keyring makes runs in your tests:

```rust
use laravel_keyring::testing::{AuthenticatorFactory, FakeIdentityProvider};
use serde_json::json;

fn app() -> laravel::Application {
    let google = FakeIdentityProvider::google().provider("google");

    my_app::configure(laravel::Application::configure().for_testing(env!("CARGO_MANIFEST_DIR")))
        .with_config(move |config, _| {
            let keyring = config.section_mut::<laravel_keyring::KeyringConfig>();
            keyring.features.sso = true;
            keyring.sso.providers.push(google);
        })
        .create()
}

#[laravel::test(app = app)]
async fn signs_in_with_google(app: laravel::Application) -> laravel::Result<()> {
    let user = create_user().await?;
    AuthenticatorFactory::sso("google", "google-42", "https://accounts.google.com", None)
        .create_for(user.id)
        .await?;

    let google = FakeIdentityProvider::google();
    google.serve().sign_in(json!({ "sub": "google-42" }));

    // GET /auth/google/redirect, then the callback `google.approve(url)` gives,
    // carrying the session cookie from the first request to the second.

    Ok(())
}
```

`provider(name)` is the `SsoProvider` to configure, as `register()`. `serve()` answers the application's requests until `stop()`, one fake at a time. `sign_in(json)` says who signs in next, `approve(url)` is the callback URL for a user who signed in at the authorization URL, and `deny(url, error)` for one who said no. `signed_in_at()`, `ignoring_reauthentication()`, `with_auth_time_claim()`, `with_key_issuer()`, and `with_claims()`, `expired()`, `unsigned()`, `signed_with_unpublished_key()`, `rotate_keys()`, `fail_exchange()` and `down()` are the PHP fake's. There's no `HostResolver` fake.

laravel-rust's test client doesn't carry cookies between requests, so carry the session cookie from the redirect to the callback yourself, as the crate's own tests do. See [Testing](https://keyringauth.com/docs/0.x/rust/testing).

## Migrating From the Socialite Recipe

The Socialite recipe was for PHP, so there's no Rust version of it to migrate from. A PHP application that migrated already has links Keyring for Rust reads, since the rows are the same.

If your Rust application stored GitHub IDs of its own, turn on `features.sso` with a `github` provider, and move each ID into a `keyring_authenticators` row as the [PHP migration](https://keyringauth.com/docs/0.x/sso#migrating-from-the-socialite-recipe) does: factor `sso`, `credential_id` from `sso::credential_id("https://github.com", &id)`, and `meta` `{ "provider", "issuer", "subject", "email" }`. For a user with no other sign-in method, `sso::link_new_account()` does it from an `Identity`.

## Reference

### The Factor

The `sso` factor is the PHP package's `SingleSignOn`, as its [reference](https://keyringauth.com/docs/0.x/sso#the-factor) describes. It has no class: `sso::has(name)`, `sso::provider(name)`, `sso::providers()`, `sso::names()` and `sso::freshness(name)` answer what the factor's methods do, and `sso::linked(&identity)` is `SingleSignOn::linked()`. The purposes are the strings `login`, `link` and `confirm`.

### Failure Reasons

`sso::SsoFailure` has the PHP package's reasons, as its [list](https://keyringauth.com/docs/0.x/sso#failure-reasons) describes. `SsoFailed::because(reason, detail)` builds one, and `expected()` says whether it's one users cause, such as `Denied` and `InvalidState`, which aren't reported.

## How It Works

The flow is the PHP package's, as its [How It Works](https://keyringauth.com/docs/0.x/sso#how-it-works) describes. Every request carries PKCE (S256), a 43-character `state` kept encrypted in the session under `keyring.sso` (five at most, the oldest making way) and claimed in the cache so it works once, even from a copy of the session, and for OpenID Connect a `nonce`, `login_hint` where there's one, and the `claims` parameter asking for `auth_time` where discovery says it's taken. The ID token has to be a compact JWS of at most 64 KiB with no `crit`, signed with RS256, PS256, ES256 or EdDSA by one of the provider's published keys that allows it, from the issuer, for this client, current within a minute, with this sign in's nonce and a subject of at most 255 bytes.

Accounts are matched on issuer and subject, stored as the PHP package's `credential_id` (`sso:` and the SHA-256 of issuer, NUL, subject) with `meta` `{ "provider", "issuer", "subject", "email" }`, so a link either side made signs in on the other.

A few things differ:

- RSA public exponents are limited to 33 bits, what the `rsa` crate takes. Every provider uses 65537.
- A discovery document or key set the PHP side cached in a store both share is read as missing and fetched again, as the two serialize differently.

See [Single Sign-On](https://keyringauth.com/docs/0.x/rust/differences#single-sign-on) for the rest.
