Single Sign-On
On this page
- Introduction
- Setting Up
- The Callback URL
- Microsoft
- GitHub
- Any OpenID Connect Provider
- Configuration
- Freshness
- Login Buttons
- Linking and Unlinking
- How It Fits With the Rest
- Second Factors and Policies
- Hearing About Accepted Identities
- Step-Up
- Users Whose Only Way In Is Never Fresh
- Password Resets and Email Changes
- Failures and the Security Log
- No Sign Up, and No Linking by Email
- Signing Up With a Provider
- Frontends Laravel Doesn't Serve
- Security Notes
- Custom Drivers
- Testing
- Migrating From the Socialite Recipe
- Reference
- The Factor
- Failure Reasons
- How It Works
Introduction
Single sign-on lets users sign in with Google, Microsoft, GitHub, or any OpenID Connect provider, such as Okta, Auth0, or Keycloak. It's a factor like any other, so you don't need Socialite or another package.
A sign-in goes through the same 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. Users link accounts from their settings while signed in. See No Sign Up, and No Linking by Email.
Setting Up
Register the factor:
use Keyring\Facades\Keyring;use Keyring\Factors; Keyring::factors([ Factors\Password::class, Factors\Totp::class, Factors\RecoveryCodes::class, Factors\WebAuthn::passkeys(), Factors\SingleSignOn::class,]);Then add each provider under sso.providers in config/keyring.php. More Identity Providers has config for GitLab, Slack, Twitch, Okta, Auth0, Keycloak, Amazon Cognito, and Salesforce, and drivers for Discord, Bitbucket, Facebook, and LinkedIn.
The Callback URL
Every provider sends the user back to the same URL, whether they're signing in, linking, or confirming: https://example.com/auth/{provider}/callback.
{provider} is the provider's key in sso.providers. Register the URL exactly as written, and add your local one too, such as http://localhost:8000/auth/google/callback. It starts at APP_URL, or at Keyring::linkRootUsing() when you set one, followed by Keyring's route prefix.
| Method | URI | Name | Does |
|---|---|---|---|
GET |
/auth/{provider}/redirect |
keyring.sso.redirect |
Sends a guest to the provider. Uses the keyring-login-options rate limiter. |
GET |
/auth/{provider}/callback |
keyring.sso.callback |
Where the provider sends the user back, to sign in, link, or confirm. |
GET |
/confirm/sso/redirect |
keyring.sso.confirm |
Sends a signed-in user to the provider of a link on the confirm page, given as authenticator. See Step-Up. |
POST |
/user/authenticators/sso |
keyring.authenticators.store |
Begins a link, with provider. See Linking and Unlinking. |
Keyring only registers the /auth and /confirm/sso/redirect routes when sso.providers lists a provider as the app boots, so an app without one keeps its own /auth/... routes. They answer 404 until the SingleSignOn factor is registered and for a provider that isn't configured. Run php artisan route:cache after adding your first provider if you cache routes.
The callback tells Keyring's own requests apart by purpose. A request your own code started with Keyring::sso() for another purpose is spent there and answered with a 404. A guest's callback uses the keyring-login-options limiter. The link and confirm callbacks of a signed-in user use keyring, while the confirm redirect uses keyring-login-options.
In the Google Cloud console, create an OAuth client ID of the "Web application" type, add the callback URL to its redirect URIs, and add the provider:
'sso' => [ 'providers' => [ 'google' => [ 'driver' => 'google', 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'), ], ],],Keyring asks for the openid, email, and profile scopes. Google's email_verified can be trusted for Gmail and Workspace addresses, and a Workspace account's domain is in the hd claim.
Google's freshness is never by default. Google only reports when the user signed in for an app with "Session age claims" turned on, and it can't be asked for a new sign-in. A user whose only way in is Google has to set a password first. Once your app has session age claims, you can set 'freshness' => 'reauthenticate'. A user still signed in at Google may then fail the confirm with StaleAuthentication, which is reported each time, until they sign out there or confirm another way.
Microsoft
In the Microsoft Entra admin center, register an application. Add a "Web" platform with the callback URL as its redirect URI, and create a client secret under Certificates & secrets:
'microsoft' => [ 'driver' => 'microsoft', 'tenant' => env('MICROSOFT_TENANT', 'common'), 'client_id' => env('MICROSOFT_CLIENT_ID'), 'client_secret' => env('MICROSOFT_CLIENT_SECRET'),],The tenant decides who can sign in:
tenant |
Who |
|---|---|
common (the default) |
Work and school accounts from any organisation, and personal Microsoft accounts. |
organizations |
Work and school accounts from any organisation. Personal accounts are refused. |
consumers |
Personal Microsoft accounts. |
| A tenant ID or domain | That one organisation's accounts. |
It has to match the account types your app registration supports. Each account keeps its own tenant's issuer, so the same subject in two tenants is two people. To admit only some organisations, check the tid claim in a custom driver.
Microsoft's freshness is reauthenticate, which needs the auth_time optional claim. Without it, no sign-in is fresh, and every confirm fails with StaleAuthentication, whose message says what to add. Add it under Token configuration, as an optional claim of the ID token type, or in the Manifest:
"optionalClaims": { "idToken": [ { "name": "auth_time", "source": null, "essential": false, "additionalProperties": [] } ]}If you can't change the registration, set 'freshness' => 'never'.
Warning
Microsoft's email claim isn't verified. In an organisation's tenant it's whatever an administrator typed. Keyring never matches on it, and marks it unverified (emailVerified is false) unless the token carries the xms_edov optional claim set to true. That claim means the tenant that owns the address's domain verified it. Add xms_edov the same way only if your own code reads emailVerified, as signing up with a provider does.
GitHub
Create an OAuth app in GitHub's developer settings, and set its "Authorization callback URL" to the callback URL:
'github' => [ 'driver' => 'github', 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'),],GitHub has no ID token, so Keyring reads who signed in from GitHub's API. The subject is the account's numeric ID, never its login, which can be renamed and taken by someone else. Keyring asks for read:user and user:email. With user:email it keeps the primary address, verified only when GitHub says so. That flag means the address was verified once, not that the account still owns it. Without it, Keyring keeps the public address, unverified. A GitHub App's user authorization works too, but its tokens carry no scopes, so it only gets the public address.
GitHub can't be asked for a new sign-in, so its freshness is never, and 'freshness' => 'reauthenticate' throws an InvalidArgumentException.
Any OpenID Connect Provider
Any provider with an OpenID Connect discovery document works with the oidc driver. Give it the issuer, and Keyring finds the rest at {issuer}/.well-known/openid-configuration:
'okta' => [ 'driver' => 'oidc', 'name' => 'Okta', 'issuer' => 'https://example.okta.com', 'client_id' => env('OKTA_CLIENT_ID'), 'client_secret' => env('OKTA_CLIENT_SECRET'),],The issuer must match the discovery document exactly, trailing slash included. The issuer and every endpoint must be HTTPS, except on localhost, 127.0.0.1, and [::1], which may use plain HTTP, such as Keycloak in Docker.
Keyring refuses a token endpoint or key set on a private, loopback, link-local (such as 169.254.169.254), multicast, or reserved address, unless it's on the issuer's own host and port. For another host inside your network, use private_endpoints.
The oidc driver defaults to reauthenticate. Keyring asks for auth_time with every sign-in only when discovery lists claims_parameter_supported. A provider that doesn't list it and leaves auth_time out of its ID tokens makes no sign-in fresh, so users must confirm at the provider before their first keyring.fresh action. For a provider that never sends auth_time, set 'freshness' => 'never'.
Configuration
These are the defaults:
'sso' => [ 'providers' => [], 'request_for' => '10m', 'cache_for' => '1h', 'store' => null,],providerslists the providers by name. Names may only hold letters, digits,-, and_, or building the provider throws anInvalidArgumentException. The login page lists them in this order.request_foris how long a user sent to a provider has to come back, as a duration. Each browser keeps up to five at once, and a newer one pushes out the oldest.cache_foris how long discovery documents and signing keys are cached. A token signed with an unknown key makes Keyring fetch the keys again, at most once a minute per provider.storeis the cache store for them.nulluses your default store.
Each provider takes these options:
| Option | |
|---|---|
driver |
oidc, google, microsoft, github, or one you registered. |
client_id |
Required. A provider without one throws an InvalidArgumentException. |
client_secret |
Leave it out for a public client, which sends only its ID. Every request uses PKCE either way. |
issuer |
The oidc driver's issuer. |
tenant |
The microsoft driver's tenant. Defaults to common. |
name |
The button's text, "Sign in with {name}". Defaults to "Google", "Microsoft", or "GitHub" for those drivers, and to the key in title case otherwise. |
scopes |
An array of strings that replaces the driver's scopes. null and empty strings are dropped, so an env() can switch one off. OpenID Connect providers always get openid. Anything else throws an InvalidArgumentException. |
parameters |
More to send the user with, such as ['prompt' => 'select_account']. It throws when it isn't an array, or sets one Keyring sends itself, such as state, nonce, redirect_uri, or max_age. A confirm's own login_hint and prompt=login take the place of yours. A claims parameter is kept. |
freshness |
How much a sign-in or confirm counts toward keyring.fresh: reauthenticate, round_trip, or never (or false). See Freshness. |
token_endpoint_auth_method |
client_secret_basic sends the secret in an Authorization header, client_secret_post in the form, and none sends only the client ID. Without it, the header is used, unless an OpenID Connect provider's discovery lists only client_secret_post. GitHub always takes the form. Other values throw an InvalidArgumentException, unless a custom driver allows them. |
private_endpoints |
true lets an OpenID Connect provider's token endpoint and key set be on a private or local address, for an issuer you run on another host inside your network, or whose DNS answers with private-looking addresses. Only for an issuer you run or trust. See Security Notes. The endpoints still have to be HTTPS. Defaults to false; anything but true or false throws an InvalidArgumentException. |
A provider that can't be built, such as one whose client_id comes from an unset env var, is left off the login page and reported to your exception handler, so the others keep working. It still fails when used: its redirect, callback, or a link started with it is a 500. A name with other characters has no redirect or callback route, so those answer 404.
Freshness
Signing in with a provider proves the user had a session there, which may be days old. Providers often let a user who's still signed in straight through. So a sign-in doesn't always count toward a fresh verification, the proof keyring.fresh asks for before changes such as adding a sign-in method or changing the password or email. Each provider's freshness says how much it counts:
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, and needs an auth_time from after the user was sent there. |
round_trip |
From when the user comes back. | A plain round trip, which counts when the user comes back. |
never (or false) |
Never. | A plain round trip that counts toward the session's level, never as fresh. Only offered toward a level. |
The defaults:
| Driver | Default | Can be reauthenticate |
|---|---|---|
oidc |
reauthenticate |
Yes |
microsoft |
reauthenticate. Add the auth_time optional claim, or no sign-in is fresh. |
Yes |
google |
never |
Only once your app has session age claims |
github |
never |
No |
| A custom driver | What its freshness() says: never for OAuth2Provider, reauthenticate for OidcProvider |
If its supportsReauthentication() says so |
The config's freshness always wins over the driver's default. Keyring::sso()->freshness('google') gives the value that counts. Asking reauthenticate of a provider that can't be asked for a new sign-in throws an InvalidArgumentException, as does any unknown value.
Warning
round_trip lets anyone at a browser still signed in to the provider get a fresh verification without typing anything. They can then add a passkey, change the password, or start an email change. A link from another site can start that confirm too. Opt in only where you accept that.
A sign-in with a never provider still signs the user in, at the assurance level it reaches. Only keyring.fresh asks for more.
Login Buttons
The login page gets a providers prop, with each provider's name, label, and url. The url starts a sign-in:
<script setup lang="ts">import type { LoginProps } from '@keyringjs/keyring' defineProps<LoginProps>()</script> <template> <a v-for="provider in providers" :key="provider.name" :href="provider.url"> Sign in with {{ provider.label }} </a></template>A plain link works best. An Inertia <Link> also works, since Keyring answers an Inertia visit with a 409 and X-Inertia-Location. Add ?remember=1 to the URL for "remember me". Keyring keeps it for the callback, and ignores a remember on the callback itself.
The list is empty until the SingleSignOn factor is registered. For your own pages, Keyring::factor('sso')->providers() returns the same list, and Keyring::sso()->names() returns the names alone.
After the provider sends the user back, the sign-in goes on as a password sign-in would. Failures return to the login page, with the error on the username field (email by default):
- An account nobody linked gets the same message as a wrong password. So does a user that
Keyring::allowSignInWhen()or a risk lock keeps out. - A provider that couldn't be reached, or a failed check, gets
keyring::keyring.sso_failed: "We couldn't sign you in with Google. Please try again." - A user who said no on the provider's page gets no error, only the
sso-cancelledstatus.
Linking and Unlinking
A user links an account at a provider from their settings page. A link is an enrollment, so it needs Features::manageAuthenticators(), a fresh verification (changes_middleware), and a verified address. While the account has an established password and no established second factor, it also takes the current password. A link signs in without a password, so a copied session could otherwise keep signing in.
The browser package's linkProvider() begins the enrollment and sends the browser to the provider:
<script setup lang="ts">import { KeyringRequestError, linkProvider } from '@keyringjs/keyring'import { router } from '@inertiajs/vue3' async function link(provider: string, password?: string) { try { await linkProvider(provider, { password }) } catch (error) { if (error instanceof KeyringRequestError && error.status === 423) { return router.visit(error.data.redirect) } throw error }}</script>Without the package, POST /user/authenticators/sso as JSON, with provider and password where needed. Open the enrollment.url in the answer with location.assign(url), not a fetch:
{ "status": "enrollment-started", "factor": "sso", "enrollment": { "provider": "google", "url": "https://accounts.google.com/o/oauth2/v2/auth?..." }}An unconfigured or unreachable provider is a 422 on provider, the latter with keyring::keyring.sso_failed. A missing or wrong password is a 422 on password.
The provider sends the user back to the callback, which finishes the link. The confirm route can't finish one. The callback checks that the same user is still signed in, the address is still verified, and the verification is still fresh. If it isn't fresh, the user confirms and returns to the callback, which still works within request_for. Then the user goes back to where they started:
authenticator-added, with the new authenticator inKeyring::result('authenticator'), named like "Google (taylor@example.com)". A security email for the new sign-in method goes out.authenticator-updatedwhen the account was already linked to this user. Only the address changes, and the provider's name too when the key the link was made with is gone.- An error on
passwordwhen the link began without a password beside an established second factor that has since gone. Begin again, with the password. - An error on
providerwhen the account belongs to someone else (keyring::keyring.sso_link_failed, which doesn't say whose), when a check fails, or when a newer link replaced this one (keyring::keyring.enrollment_expired). A callback afterrequest_forfails withenrollment_expiredstraight away. - A callback this browser has no request for fails with
sso_failedonproviderand goes tohome, or during a confirm, back to the confirm page withkeyring::keyring.expiredon the username field. Nothing is logged for either. sso-cancelled, with no error, when the user said no.
A user can link any number of accounts. Each is an authenticator, and present() adds the provider and the email the provider last gave:
{ "factor": "sso", "id": "01JC6...", "name": "Google (taylor@example.com)", "createdAt": "2026-11-26T09:12:00+00:00", "lastUsedAt": null, "provider": "google", "email": "taylor@example.com" }To show which providers a user may link, pass Keyring::factor('sso')->providers() to the settings page, and use each one's name and label. Keyring updates the address on each sign-in, and uses it for nothing else. To unlink, remove the authenticator with DELETE /user/authenticators/{authenticator} (removeAuthenticator(id) in the browser package). Removing the user's last way to sign in is refused with keyring::keyring.last_factor.
A link counts toward the freeze like any other method. A new one freezes the account for 7 days, so a copied session that linked it can't remove the owner's established methods, though the owner can unlink a new one whenever they like. Once a link is 7 days old, unlinking it while the account is frozen needs an established key. A link never proves a change, and doesn't make a policy ask for more.
How It Fits With the Rest
Second Factors and Policies
A sign-in with a provider is one knowledge proof, like a password. Keyring doesn't count what the provider did. If the provider asked for a second factor, Keyring still asks for the user's own, as your policy says.
A link is never a second factor:
- It gives no recovery codes, and a user who removes their last authenticator app loses their recovery codes, whatever they've linked.
- It never stands in for the established second factor that lets a sign-in method be added without the password.
- It's never the default or offered on the challenge page. Setting
defaulton one is refused.
A provider's amr and acr never count toward the level either, so an amr of mfa doesn't make a sign-in a second factor. They're kept on the session's Verification, as How It Works describes.
Hearing About Accepted Identities
Keyring\Events\ProviderIdentityAccepted fires each time a provider's account is accepted as one of the user's links. Its purpose is one of the factor's constants:
purpose |
When |
|---|---|
SingleSignOn::LOGIN (login) |
A sign-in, once its account matched a link of a user who may sign in. An account nobody linked fires nothing. |
SingleSignOn::CONFIRM (confirm) |
A confirm brought back the account of the link it was started for. |
SingleSignOn::LINK (link) |
A link was added, or an existing one updated. A link refused because someone else holds the account fires nothing. |
It carries the user, the authenticator, the identity (Keyring\Sso\Identity, with amr, acr, authTime, and claims), and the purpose.
For a sign-in or confirm, it fires before the rest of the pipeline. The user may still need a second factor, or be refused by a risk lock, so wait for Authenticated or Confirmed to know they're signed in.
A listener in the request sees the identity's request, with its state, nonce, and PKCE verifier. A queued listener gets those three blank, and the ID token's nonce, at_hash, and c_hash removed from the claims.
Step-Up
A link answers the confirm page like any other method. Its challenge prop holds the provider, its label, and the url of the keyring.sso.confirm route. Send the browser there, or call the browser package's confirmWithProvider(). The provider has to bring back the same account as the link, for the same user, while the confirm is in progress. The callback then confirms through the confirm page's pipeline, so rate limits, events, and the security log apply.
A failure, or a callback after request_for, goes back to the confirm page with the error on the username field (email). A user who says no gets sso-cancelled. A link is only offered while its provider is configured and the keyring.sso.confirm route is registered. A user held for a new password can still confirm this way.
How much it proves depends on the provider's freshness. If the link's provider and the one a sign-in came through differ, the stricter counts.
reauthenticate, the default for OpenID Connect providers and Microsoft: a sign-in counts from when the user last signed in at the provider (auth_time), not from when they came back. Keyring asks forauth_timewith every sign-in where the provider takes theclaimsparameter, as Google does and as an OpenID Connect provider whose discovery listsclaims_parameter_supporteddoes. Elsewhere the provider may leave it out, and a sign-in without anauth_timenever counts as recent. A confirm asks for a new sign-in whatever session the user has (max_age=0, andprompt=loginwhere taken). It counts only whenauth_timeis no earlier than when the user was sent, give or take a minute. A missing or olderauth_timefails withSsoFailure::StaleAuthentication, which is reported. The session's assurance level and timeouts still start when the user comes back, andkeyring.freshstill asks a user at a browser that's signed in at the provider to confirm.never, the default for Google, GitHub, and drivers built onOAuth2Provider: a sign-in never counts as recent, and nor does a confirm. A confirm is recorded at an unknown time (Verification::UNKNOWN), so the confirm page offers the link only toward a level, andGET /confirm/sso/redirectanswers404for a fresh verification.round_trip, only when you set it:auth_timeis ignored, and a sign-in and a confirm both count when the user comes back. A confirm may let a user still signed in at the provider straight through. It's a known limitation of opting in.
A removed provider's links can't confirm anything, so move its users to another method before you remove it, such as asking them to set a password. How a link follows its provider's key is in How It Works.
A confirm builds on what the user already proved. A user who signed in with GitHub, skipped their authenticator app because your policy let them, and opens a page behind keyring:aal2, is asked for the app alone. Once AAL2 has lapsed (an hour idle by default, sessions.levels.aal2.idle), the confirm page offers the GitHub link beside the app, so they confirm with both.
A page behind keyring.fresh counts only what can be proved recently, so a GitHub link is left out there. Laravel's password.confirm is a freshness check too: its /confirm page doesn't offer never links, and a round trip never sets auth.password_confirmed_at. See Laravel's Password Confirmation. StepUp::unlessMet() asks for a level and a moment together only when the account can freshly prove the level, and otherwise asks for the level first.
Users Whose Only Way In Is Never Fresh
A user whose only sign-in method is a link at a never provider, such as Google or GitHub by default, or a removed provider, can sign in, but can't pass keyring.fresh. They can't add another method either, so they get the enroll-first answer at once, with no confirm page: a redirect to your enrollment_url with the enroll-first status, or a 403 for JSON. A user with a second factor, such as an authenticator app, confirms with that instead.
A user who loses that app is stuck in the same way. Their recovery codes still sign them in beside the link, but the confirm page doesn't offer them, since a recovery code never stands in for the only factor a fresh verification asks for.
The way out is a password reset, with Features::resetPasswords() on. They sign out first, because /forgot-password is for guests, reset the password, and sign in with it. The password and a recovery code then remove the lost app. The reset unlinks every provider, so they link the provider again afterwards. On your enrollment page, tell a user without a password ($user->getAuthPassword() is empty) to sign out and reset it.
Keyring only links a provider for a user already signed in with a fresh verification, so this mostly happens when your code links users, or you change a provider's freshness to never. A new account from signing up with a never provider has nothing else, so have the user 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, since each link stands in for the password. A second factor stays. Each removed link is logged and announced, even while the SingleSignOn factor isn't registered, since a link left behind would come back with it.
An undone email change removes the links added since the change, and keeps the older ones. The sso factor key is Keyring's: a factor of your own with that key would have its authenticators removed by a password reset too.
Failures and the Security Log
- A failed sign-in, such as an unlinked account or a failed callback check, is logged as
factor_failedwith thessofactor, and dispatchesFactorFailedand Laravel'sFailed. The callback has no username field, soFailed's credentials name a user only when one was found. Keyring never takes a username from the query string. - A failed second factor after a provider sign-in is logged as
second_factor_failed. Thesecond_factor_failedemail names the link they signed in with. - A refused link is logged as
enrollment_refused, with reasoninvalid, ornot_allowedfor an unverified address, and dispatchesEnrollmentRefused. - A user who said no isn't logged. A sign-in logs
signed_inwith the factorsso, and adding or removing a link logsauthenticator_addedorauthenticator_removed.
A failure is a Keyring\Exceptions\SsoFailed, whose reason is a Keyring\Enums\SsoFailure (see Failure Reasons). Its message never carries a code, token, or secret, so it's safe to log. Keyring catches it in its own routes, where users only see sso_failed, and reports it to your exception handler. Denied and InvalidState aren't reported, since users cause those by saying no or coming back late. SsoFailed::expected() says which, for your own routes.
No Sign Up, and No Linking by Email
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. Some providers let an account carry an address its owner hasn't proven, so linking by address would let someone sign in as whoever has that address in your app.
Users register as they do today, through Keyring's registration or your own, and link a provider afterwards. To let people sign up with a provider, build the routes yourself, as below.
Signing Up With a Provider
Keyring::sso() sends users to a provider and takes them back from your own routes. start() returns the URL and keeps the request in the session. complete() checks the callback and returns the Keyring\Sso\Identity the provider vouched for, with its issuer, subject, email, emailVerified, name, and claims. These routes create the account, link it, and sign the new user in. Someone who already signed up is signed in through Keyring's pipeline instead:
use App\Models\User;use Illuminate\Http\Request;use Illuminate\Support\Facades\DB;use Illuminate\Validation\ValidationException;use Keyring\Exceptions\SsoFailed;use Keyring\Facades\Keyring;use Keyring\Factors\SingleSignOn;use Keyring\Login\Registration;use Keyring\Login\SignIn;use Keyring\Login\Verification; Route::middleware('guest')->group(function () { Route::get('/sign-up/google', fn () => redirect()->away( Keyring::sso()->start('google', 'sign-up', route('sign-up.google.callback')), ))->name('sign-up.google'); Route::get('/sign-up/google/callback', function (Request $request) { try { $identity = Keyring::sso()->complete($request, 'google'); } catch (SsoFailed) { return to_route('register')->withErrors(['email' => 'We couldn\'t sign you up with Google.']); } abort_unless($identity->request->purpose === 'sign-up', 404); try { // Someone who already signed up: an ordinary sign in. if (Keyring::factor(SingleSignOn::KEY)->linked($identity) !== null) { $request->attributes->set(SingleSignOn::IDENTITY, $identity); return Keyring::attempt($request, SingleSignOn::KEY); } $email = $identity->email === null ? null : Keyring::normalizeUsername($identity->email); // 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. $vouched = $identity->emailVerified && $email !== null && (str_ends_with($email, '@gmail.com') || (is_string($identity->claims['hd'] ?? null) && $identity->claims['hd'] !== '')); if (! $vouched || app(Registration::class)->taken($email)) { return to_route('register')->withErrors(['email' => 'Sign up with your email address, then link Google from your settings.']); } [$user, $link] = DB::transaction(function () use ($identity, $email) { $user = User::create(['name' => $identity->name ?? $email, 'email' => $email, 'password' => null]); $user->forceFill(['email_verified_at' => now()])->save(); return [$user, $user->authenticators()->create([ 'factor' => SingleSignOn::KEY, 'name' => "Google ({$email})", 'credential_id' => SingleSignOn::credentialId($identity->issuer, $identity->subject), 'confirmed_at' => now(), 'meta' => ['provider' => 'google', 'issuer' => $identity->issuer, 'subject' => $identity->subject, 'email' => $identity->email], ])]; }); // 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. app(SignIn::class)->as($request, $user, [Verification::of($link)]); } catch (ValidationException $e) { return to_route('login')->withErrors($e->errors()); } return redirect('/settings/security'); })->middleware('throttle:keyring-login-options')->block()->name('sign-up.google.callback');});Keep these in mind:
- Register
https://example.com/sign-up/google/callbackwith the provider too. Don't put your own routes under/auth/{provider}/, which is Keyring's. - Only take an address the provider is the authority for. Google says that
emailVerifiedalone isn't enough: it vouches for@gmail.comand Workspace (hd) accounts. Any other address was verified once and may have changed hands. Without that check, someone who once hadtaylor@example.comcould sign up as Taylor, and a passkey they add during the sign up would survive Taylor's password reset, which only unlinks providers. Microsoft'semailVerifiedis rarelytrue. When in doubt, refuse, or create the account unverified and send Laravel's verification email first. - Never take over an account that already has the address.
Registration::taken()also counts accounts your global scopes hide. Run the address throughKeyring::normalizeUsername()before you look it up or store it. - The user and the link are created in one transaction. The callback uses
keyring-login-options, since each call may create an account. - The new user has no password, so
passwordmust be nullable. Google'snevermeans later Google sign-ins aren't fresh, so the account is signed in withSignIn::as(), and the sign up counts as a fresh verification. - Someone signed in to the victim's Google account could create the account first, then set a password or passkey within that window. Both are announced to the address Google vouched for. Send new users to your settings page to set a password or add a passkey within the 15 minutes
keyring.freshgives. - Only a new account goes through
SignIn::as(). Everyone else goes throughKeyring::attempt(), with the identity on the request underSingleSignOn::IDENTITY, so their second factor is asked for. Never callSignIn::as()for an existing account. See Starting a Sign In Yourself. - Store the link with
SingleSignOn::credentialId(), as the example does, so Keyring's own button signs the same user in and a password reset unlinks it. - The request has the purpose
sign-up. Start your own requests with a purpose other thanlogin,link, orconfirm. Keyring's callback tells its own requests by purpose, and spends and 404s any other.
Frontends Laravel Doesn't Serve
A headless frontend, such as a Nuxt app on app.example.com, can offer providers too. A JSON request to the redirect route answers with the provider's URL, so the frontend can send the browser there. The browser package's signInWithProvider() does both:
import { signInWithProvider } from '@keyringjs/keyring' await signInWithProvider('google', { remember: true })Start the callback URL at the frontend with Keyring::linkRootUsing(), and register it with the provider. With the auth prefix, that's https://app.example.com/auth/auth/google/callback. The frontend serves a page there that passes the path and query to Laravel as JSON:
import { json, routes } from '@keyringjs/keyring' const answer = await json('GET', routes.ssoCallback('google') + location.search)Each answer is the one a sign-in gives:
| Purpose | Answer |
|---|---|
| Sign-in | authenticated with its alerts; a 202 naming the challenge page; a 422 on the username field; or sso-cancelled with page: "login". |
| Link | authenticator-added or authenticator-updated with the authenticator; a 422 on provider; or a 423 when the verification is no longer fresh. After a 423, send the user to confirm, then back to the same callback URL, which still finishes the link within request_for. |
| Expired request | A 422: on provider for a link, on the username field for a confirm. |
| Used up, or not this browser's | A 422 on the username field during a confirm, and on provider otherwise. |
| Held for a new password | A confirm's callback answers as above. Any other gets a 403 with change-password. |
| Confirm | authenticated with the redirect to carry on to; a 422 on the username field (429 when rate limited); or sso-cancelled with page: "confirm". |
JSON request to keyring.sso.confirm |
The provider's url. |
Security Notes
private_endpointsturns off the inward-address check for one provider. Its discovery document can then aim Keyring's requests, with the client secret, at anything your server can reach over HTTPS. Set it only for an issuer you run or trust that far, never for one users or tenants can choose.- Cookies. Keep
SESSION_SAME_SITEatlax. Withstrict, the browser drops the session cookie on the return from the provider, and every callback fails. With thecookiesession driver, Keyring also marks eachstateused in the cache store thatcache.limiternames, so on more than one server that store must be shared, such as Redis or the database. - Brokers. An Okta, Auth0, Keycloak, or Cognito that sends users on to another provider may stamp a new
auth_timeafter a silent round trip there. Soreauthenticateonly means something when users type their credentials at the broker. See Picking a Freshness. - RS256. Google and Microsoft sign their ID tokens with RS256 alone, so Keyring accepts it, though not for passkeys by default. If you assess against ASVS, note it under 11.6.1.
- Sessions. Keyring's session carries on after the provider's session ends, and signing out of one doesn't sign the user out of the other.
Custom Drivers
Keyring::sso()->extend() registers a driver of your own, or replaces one of Keyring's. The resolver gets the provider's config and name, and returns a Keyring\Contracts\IdentityProvider. Call it in your KeyringServiceProvider's boot() method. This one only lets in accounts from one Google Workspace domain:
use Keyring\Enums\SsoFailure;use Keyring\Exceptions\SsoFailed;use Keyring\Facades\Keyring;use Keyring\Sso\AuthorizationRequest;use Keyring\Sso\Identity;use Keyring\Sso\Providers\GoogleProvider; Keyring::sso()->extend('workspace', fn (array $config, string $name) => new class($name, $config) extends GoogleProvider{ protected function identityFrom(AuthorizationRequest $request, array $tokens, array $query): Identity { $identity = parent::identityFrom($request, $tokens, $query); if (($identity->claims['hd'] ?? null) !== $this->config['domain']) { throw SsoFailed::because(SsoFailure::InvalidToken, "[{$this->name}] signed in an account outside the workspace."); } return $identity; }});Configure it like any other provider:
'staff' => [ 'driver' => 'workspace', 'name' => 'Acme Staff', 'domain' => 'acme.com', 'parameters' => ['hd' => 'acme.com'], 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'),],For an OAuth 2.0 provider without OpenID Connect, extend Keyring\Sso\Providers\OAuth2Provider, as the GitHub driver does. It handles the state, PKCE, the code exchange, and client authentication. You supply authorizationEndpoint(), tokenEndpoint(), defaultScopes(), and identityFrom(), which reads who signed in, usually from the provider's API with Metadata::http()->withToken(...). Use the account's permanent ID as the subject, never a username or an address, and set emailVerified only when the provider says so. More Identity Providers has complete drivers and a checklist.
The IdentityProvider contract has six methods:
name()must return the key the provider is configured under, andlabel()the button's text.supportsReauthentication()istrueonly for a provider that sendsauth_timeand honours amaxAgeof0.freshness()is the defaultKeyring\Enums\SsoFreshness. ReturnReauthenticateonly wheresupportsReauthentication()istrue, and Keyring counts a sign-in from itsauthTime.authorizationUrl()builds the URL from the request's state, nonce, PKCE challenge,maxAge, andloginHint.identify()turns the callback into anIdentity, withauthTimewhen the provider says when the user signed in. Otherwise it throwsSsoFailed.
The config's freshness wins over your driver's default, for any driver, and an unknown value is refused. Keyring::sso()->freshness($name) is what Keyring goes by. OAuth2Provider and OidcProvider read the option the same way, with defaultFreshness() for when the config says nothing. Google and Microsoft override reauthenticationParameters() to say what a new sign-in sends.
Keyring::sso()->start() also takes $maxAge and $loginHint, for your own routes. Asking a provider that can't be asked for a new sign-in throws an InvalidArgumentException. With $maxAge, the user has to have signed in at the provider no more than that many seconds before they were sent, and complete() refuses an identity whose authTime is missing, older, or in the future, with SsoFailure::StaleAuthentication. The $loginHint goes to an OpenID Connect provider as login_hint.
Testing
Keyring\Testing\FakeIdentityProvider stands in for a provider. It answers Keyring's requests through Http::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. register() adds it to sso.providers, and the sso() factory state links an account to a user:
use Keyring\Enums\Assurance;use Keyring\Models\Authenticator;use Keyring\Sso\Providers\GoogleProvider;use Keyring\Testing\FakeIdentityProvider; it('signs in with Google', function () { $google = FakeIdentityProvider::google()->register('google'); $user = User::factory()->create(); Authenticator::factory()->sso('google', subject: '42', issuer: GoogleProvider::ISSUER)->for($user, 'authenticatable')->create(); $url = $this->get(route('keyring.sso.redirect', 'google'))->headers->get('Location'); $this->get($google->signIn(['sub' => '42'])->approve($url))->assertRedirect('/dashboard'); $this->assertAuthenticatedAs($user);}); it('links a Google account', function () { $google = FakeIdentityProvider::google()->register('google'); $user = User::factory()->create(); $url = $this->actingAs($user)->withAssurance(Assurance::AAL1) ->postJson(route('keyring.authenticators.store', 'sso'), ['provider' => 'google', 'password' => 'password']) ->json('enrollment.url'); $this->get($google->approve($url))->assertSessionHas('status', 'authenticator-added');});| Method | |
|---|---|
new FakeIdentityProvider(), ::google(), ::microsoft($tenant = 'common'), ::github() |
A provider for that driver. The plain one is an OpenID Connect provider at https://idp.test, whose default user matches the sso() factory state. |
register($name = 'fake', $config = []) |
Adds it to sso.providers, with its client's credentials and anything in $config. |
signIn(array $user, ?array $emails = null) |
Who signs in next: the ID token's claims, or for GitHub the user and its addresses. |
approve($url) |
The callback URL for a user who signed in at the authorization URL Keyring sent them to. |
deny($url, $error = 'access_denied') |
The callback URL for a user who said no, or another error. |
signedInAt($at) |
The user already has a session at the provider from then, and is let straight through with that auth_time until a request asks for a new sign-in. Without it, they sign in at the first approve(). |
ignoringReauthentication() |
Keeps letting the user through on that session when a new sign-in is asked for, as a provider that ignores prompt=login would. |
withAuthTimeClaim() |
The fake Microsoft sends auth_time once the app registration adds the optional claim, and leaves it out without. The fake Google sends it only when the claims parameter asks for it. |
withKeyIssuer($issuer) |
The issuer its keys name. The fake Microsoft names https://login.microsoftonline.com/{tenantid}/v2.0 by default, the template its multi-tenant keys use. Use this to test how Keyring handles keys that name another issuer. null names none. |
withClaims(), expired(), unsigned(), signedWithUnpublishedKey(), rotateKeys(), failExchange(), down() |
Tokens and answers Keyring should refuse, for testing your error pages. withClaims(['auth_time' => null]) leaves auth_time out. |
Keyring refuses token endpoints and key sets that resolve inside your network, so it looks names up with Keyring\Sso\HostResolver. A FakeIdentityProvider swaps in HostResolver::fake() unless your test already did, so no test asks your DNS about idp.test. In your own tests without the fake, call HostResolver::fake(['idp.example.com' => ['10.0.0.5']]) yourself.
To test a confirm, follow the confirm page's challenge.url. Google's freshness is never by default, so register it with ['freshness' => 'reauthenticate'] to test a new sign-in, or ['freshness' => 'round_trip'] to test a plain round trip:
it('confirms with Google', function () { $google = FakeIdentityProvider::google()->register('google', ['freshness' => 'reauthenticate']); $user = User::factory()->create(['password' => null]); Authenticator::factory()->sso('google', subject: '42', issuer: GoogleProvider::ISSUER)->for($user, 'authenticatable')->create(); $this->actingAs($user)->withAssurance(Assurance::AAL1)->freshAt(now()->subHour()); $this->postJson(route('keyring.authenticators.store', 'totp'))->assertStatus(423); $page = $this->getJson(route('keyring.confirm.challenge'))->json('props.challenge.url'); $url = $this->get($page)->headers->get('Location'); $this->get($google->signIn(['sub' => '42'])->approve($url))->assertRedirect(); $this->postJson(route('keyring.authenticators.store', 'totp'))->assertOk();});Create the fake before any catch-all Http::fake() of your own, which would otherwise answer its requests first. Keyring registers its /auth routes as the app boots, so keep the provider in config/keyring.php too. register() replaces the credentials, so they may be empty while testing.
Migrating From the Socialite Recipe
Earlier versions of these docs had a recipe that signed in with GitHub through Socialite, with a factor of your own and a github_id column. The SingleSignOn factor replaces it:
- Add the
githubprovider tosso.providers, and registerSingleSignOnin place of your GitHub factor. - Remove the recipe's routes. Keyring's callback for a provider named
githubis/auth/github/callback, the path the recipe used too, so the two would collide. The GitHub app's callback URL can stay as it is, and/settings/github/callbackisn't needed any more. - Move each
github_idinto a link, in a migration:
use App\Models\User;use Keyring\Factors\SingleSignOn;use Keyring\Sso\Providers\GitHubProvider; User::query()->whereNotNull('github_id')->eachById(function (User $user) { $subject = (string) $user->github_id; $user->authenticators()->firstOrCreate( ['factor' => SingleSignOn::KEY, 'credential_id' => SingleSignOn::credentialId(GitHubProvider::ISSUER, $subject)], ['name' => 'GitHub', 'confirmed_at' => now(), 'meta' => ['provider' => 'github', 'issuer' => GitHubProvider::ISSUER, 'subject' => $subject, 'email' => null]], );});The provider name, github here, has to be the one sign-in sso.providers. The address fills in the next time each user signs in.
Each link is dated when the migration runs. An undone email change removes the sign-in methods added since the change, so undoing a change made before the migration also removes the link. The user links GitHub again afterwards. Don't backdate created_at to avoid that, since a link someone else added after taking the account would then survive the undo.
- Remove the listener that cleared
github_idonPasswordResetandEmailChangeReverted. Keyring now unlinks every provider on a reset, and an undone email change removes the links added since. Then drop the column. - Replace
Socialite::fake()in your tests withFakeIdentityProvider::github().
Reference
The Factor
| Key | sso |
| Categories | knowledge: it stands in for the password, so it counts as the same kind of proof |
| Starts a sign-in | yes, from the provider's callback |
| Answers a challenge | no |
| Answers a confirm | by going back to the provider, as its freshness says. With never, the default for Google and GitHub, it's a plain round trip that counts toward a level such as AAL2, never toward a fresh verification. See Step-Up |
| Users add it | yes, one for each account they link |
| Recovery codes, default | neither: a link never comes with recovery codes, and is never the default |
| Priority | 30 |
Failure Reasons
The reason of a Keyring\Exceptions\SsoFailed is one of these Keyring\Enums\SsoFailure cases:
| Reason | Meaning |
|---|---|
Denied |
The user said no at the provider. Not reported. |
InvalidState |
The callback's state is missing, unknown, already used, expired, or was started for another provider. Not reported. |
ProviderError |
The provider answered the callback with an error of its own. |
InvalidResponse |
The callback isn't one the provider would send: no code, or an iss that isn't the provider's. |
ExchangeFailed |
The code couldn't be exchanged for tokens. |
InvalidToken |
An ID token failed a check: its signature, issuer, audience, times, or nonce. Also a token endpoint that sent no ID token, or an ID token with no subject. |
Unavailable |
The provider's metadata, keys, or user API couldn't be read, or its discovery document was refused: another issuer, a non-HTTPS endpoint, or a private address. |
StaleAuthentication |
A sign-in asked for with max_age came back with a missing or too old auth_time. |
How It Works
Inner workings, for when you need to know why something is refused.
- The callback. Each
stateis usable once, by the browser whose session started it, for the provider it was started with, beforerequest_forruns out. An unknown, used, or expiredstateisSsoFailure::InvalidState. Requests carry a PKCE challenge (S256), and an OpenID Connect request carries anoncethat the ID token has to repeat. - Accounts. An account is the pair of its issuer and subject. Keyring stores a hash of the pair as the link's credential ID and never looks at the address. A provider that changes its issuer, or a Microsoft user who moves tenant, is a new account.
- ID tokens are checked as OpenID Connect Core asks: signed by a published key with RS256, PS256, ES256, or EdDSA (never
noneor a shared secret), from the configured issuer, for your app (audandazp), current within a minute of clock drift, with the request's nonce. The signature is checked even though the token came straight from the provider. - Mix-up. A callback whose
issnames another issuer (RFC 9207) is refused before its code goes anywhere, and so is one withoutissfrom a provider whose discovery says it always sends one. - Addresses. Keyring won't send its token and key requests to a private, loopback, link-local, or otherwise non-public address, unless it's on the issuer's own host and port. It checks a name when it looks it up, and the HTTP client looks it up again, so a DNS answer that changes between the two isn't caught. Keyring follows no redirects from a provider.
- Caching. A discovery document is cached only once it names the configured issuer and HTTPS endpoints, and a key set only once it holds a key.
- Provider claims. The provider's
amrandacrare kept on the session'sVerificationasproviderAmrandproviderAcr, for an app that reports how the user signed in. At most 10 distinctamrvalues are kept, and anacronly if it's printable ASCII of up to 255 characters with no spaces. Neither counts toward the level. - Link keys. A link keeps its provider's key while that key is configured. Until the key is gone, a sign-in under another key with the same issuer counts for no more than the stricter of the two
freshnessvalues. Once it's gone, a sign-in through the new key moves the link to it.