Signing InMore Identity Providers

More Identity Providers

On this page

Introduction

Single Sign-On covers Google, Microsoft and GitHub. This page covers the rest. Most providers speak OpenID Connect, so they need only keyring.OIDCProvider and a few fields. A provider that only speaks OAuth 2.0 needs a small driver of your own.

What each provider needs registered with it, its issuer and its freshness are the same as in the PHP docs, which say what was checked and when. The PHP examples run in the PHP package's test suite. The Go ones on this page are translations: check them against your provider before relying on them.

Provider How Freshness
GitLab oidc Never
Slack oidc Never
Twitch oidc Never
Okta oidc Reauthenticate (the default)
Auth0 oidc Reauthenticate (the default)
Keycloak oidc Reauthenticate (the default)
Amazon Cognito oidc Reauthenticate with managed login, Never with the classic hosted UI
Salesforce oidc Never
Discord, Bitbucket, Facebook, LinkedIn a driver Never
Apple not supported

Picking a Freshness

A provider's Freshness says how much a sign in or confirm through it counts toward a fresh verification. keyring.OIDCProvider 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 explain how to choose, and how to check the choice, and hold here. A provider that doesn't do both should use Freshness: keyring.Never.

OpenID Connect Providers

Every provider here takes 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:

Go
gitlab := keyring.OIDCProvider("gitlab", "https://gitlab.com", os.Getenv("GITLAB_CLIENT_ID"), os.Getenv("GITLAB_CLIENT_SECRET"))gitlab.Label = "GitLab"gitlab.Freshness = keyring.Never cfg.SSO.Providers = append(cfg.SSO.Providers, gitlab)

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.

Slack

The same shape, with the issuer https://slack.com and Never. Slack's settings and scopes are in the PHP docs.

Twitch

The same shape, with the issuer https://id.twitch.tv/oauth2 and Never. Twitch's claims and scopes are in the PHP docs.

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 for the issuer to pick, and the note on brokers in 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.

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.

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.

Salesforce

The same shape, with https://login.salesforce.com (or your My Domain) as the issuer and Never. See the PHP docs.

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. Keyring for Go doesn't export the OAuth 2.0 base its GitHub driver is built on (the PHP package's OAuth2Provider), so a driver builds the authorization URL, checks the callback and exchanges the code itself. That's short, as the Discord driver shows. Keyring still makes the state, the PKCE verifier and the nonce, keeps the request in the session, and checks the state when the user comes back, before your driver's Identify runs.

Each driver keeps the account's permanent ID as the subject, never a username or an address, and sets EmailVerified 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:

Go
k := keyring.New[models.User](func(cfg *keyring.Config) {	cfg.Factors.SingleSignOn = true 	cfg.SSO.Extend("discord", func(provider keyring.SSOProvider) (keyring.IdentityProvider, error) {		return NewDiscord(provider)	})	cfg.SSO.Providers = append(cfg.SSO.Providers, keyring.SSOProvider{		Name:         "discord",		Driver:       "discord",		ClientID:     os.Getenv("DISCORD_CLIENT_ID"),		ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),	})})

Label, Scopes, Parameters, Freshness and TokenEndpointAuthMethod are there for your driver to read, as are ClientID and ClientSecret. Keyring checks the name, that the freshness (the config's, else the driver's) is one of the three, and that a driver reporting Reauthenticate can reauthenticate; the rest is up to the driver. Issuer, Tenant and PrivateEndpoints 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:

Go
package sso import (	"context"	"encoding/json"	"fmt"	"net/http"	"net/url"	"strings"	"time" 	"go.laravel.com/httpclient" 	keyring "keyringauth.com/go") // The issuer of every Discord link: never change it once users have linked// accounts.const discordIssuer = "https://discord.com" type Discord struct {	provider keyring.SSOProvider} func NewDiscord(provider keyring.SSOProvider) (*Discord, error) {	if provider.ClientID == "" {		return nil, fmt.Errorf("identity provider [%s] needs a client ID", provider.Name)	} 	return &Discord{provider: provider}, nil} func (d *Discord) Name() string {	return d.provider.Name} func (d *Discord) Label() string {	if d.provider.Label != "" {		return d.provider.Label	} 	return "Discord"} // Plain OAuth 2.0 can't be asked for a new sign in, nor say when there was// one.func (d *Discord) SupportsReauthentication() bool {	return false} func (d *Discord) Freshness() keyring.SSOFreshness {	return keyring.Never} func (d *Discord) AuthorizationURL(_ context.Context, request keyring.AuthorizationRequest) (string, error) {	scopes := d.provider.Scopes	if scopes == nil {		scopes = []string{"identify", "email"}	} 	query := url.Values{}	for _, parameter := range d.provider.Parameters {		query.Set(parameter.Name, parameter.Value)	}	// What every request carries, over anything the config says.	query.Set("response_type", "code")	query.Set("client_id", d.provider.ClientID)	query.Set("redirect_uri", request.RedirectURI)	query.Set("scope", strings.Join(scopes, " "))	query.Set("state", request.State)	query.Set("code_challenge", request.CodeChallenge())	query.Set("code_challenge_method", "S256") 	return "https://discord.com/oauth2/authorize?" + query.Encode(), nil} func (d *Discord) Identify(ctx context.Context, request keyring.AuthorizationRequest, query keyring.CallbackQuery) (*keyring.Identity, error) {	if query.Has("error") {		if said, _ := query.String("error"); said == "access_denied" {			return nil, keyring.NewSSOFailed(keyring.SSODenied, "The user declined to sign in with Discord.")		} 		return nil, keyring.NewSSOFailed(keyring.SSOProviderError, "Discord answered with an error.")	}	code, ok := query.String("code")	if !ok || code == "" {		return nil, keyring.NewSSOFailed(keyring.SSOInvalidResponse, "The callback from Discord has no code.")	} 	// The code, exchanged with PKCE, the credentials in the form.	res, err := discordHTTP().Form(url.Values{		"grant_type":    {"authorization_code"},		"code":          {code},		"redirect_uri":  {request.RedirectURI},		"code_verifier": {request.CodeVerifier},		"client_id":     {d.provider.ClientID},		"client_secret": {d.provider.ClientSecret},	}).Post(ctx, "https://discord.com/api/oauth2/token")	if err != nil || !res.Successful() {		return nil, keyring.NewSSOFailed(keyring.SSOExchangeFailed, "Discord's token endpoint refused the code.")	}	var tokens struct {		AccessToken string `json:"access_token"`		Error       string `json:"error"`	}	if json.Unmarshal(res.Body, &tokens) != nil || tokens.Error != "" || tokens.AccessToken == "" {		return nil, keyring.NewSSOFailed(keyring.SSOExchangeFailed, "Discord's token endpoint sent no access token.")	} 	// Who signed in. Never the token in a message.	res, err = discordHTTP().Token(tokens.AccessToken).Get(ctx, "https://discord.com/api/v10/users/@me")	if err != nil || !res.Successful() {		return nil, keyring.NewSSOFailed(keyring.SSOUnavailable, "Discord's API could not be read at [/users/@me].")	}	var user map[string]any	if json.Unmarshal(res.Body, &user) != nil {		return nil, keyring.NewSSOFailed(keyring.SSOUnavailable, "Discord's API did not answer with JSON at [/users/@me].")	} 	// The permanent ID, never the username.	id, _ := user["id"].(string)	if id == "" {		return nil, keyring.NewSSOFailed(keyring.SSOUnavailable, "Discord named no account.")	} 	identity := &keyring.Identity{Request: request, Provider: d.Name(), Issuer: discordIssuer, Subject: id, Claims: user}	if email, ok := user["email"].(string); ok && email != "" {		identity.Email = &email		// "verified", whether Discord has verified it, and only the boolean.		identity.EmailVerified = user["verified"] == true	}	if name, ok := user["global_name"].(string); ok {		identity.Name = name	} 	return identity, nil} // discordHTTP is a client with short timeouts that follows no redirects, as// Keyring's own drivers use.func discordHTTP() *httpclient.Client {	return httpclient.AcceptJSON().		ConnectTimeout(5 * time.Second).		Timeout(10 * time.Second).		CheckRedirect(func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse })}

discordHTTP starts from your application's HTTP client, so any headers, tokens or retries you give that client in laravel.Options.HTTP go to Discord too. Keyring's own drivers leave them behind.

Keyring sets the identity's Provider and Request to the ones it knows whatever the driver says, and refuses one with no issuer or subject.

Bitbucket

There's no Go driver written for Bitbucket yet. Build one as Discord's is, with the endpoints, scopes and fields the PHP driver uses: its subject is the account's uuid, and its addresses come from a second API call.

Facebook

There's no Go driver written for Facebook yet. Build one as Discord's is, with the endpoints and fields the PHP driver uses. Facebook never says whether an address is verified, so EmailVerified is always false.

LinkedIn

There's no Go driver written for LinkedIn yet. LinkedIn's OpenID Connect tokens don't carry the nonce Keyring requires, so the PHP driver 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 holds, in Go terms:

  1. Send the user to the provider's authorization endpoint with response_type=code, the client ID, the request's RedirectURI, the scopes, its State, and CodeChallenge() with code_challenge_method=S256. Put the config's Parameters first, so they can't replace these.
  2. In Identify, answer an error in the callback with SSODenied for access_denied and SSOProviderError otherwise, and a missing code with SSOInvalidResponse.
  3. Exchange the code with the request's RedirectURI and CodeVerifier. Send the secret in the way the provider takes it: BasicAuth on the client for client_secret_basic, each half form-encoded, or the form for client_secret_post. Some providers answer a refused code with a 200 and an error in the body: read it as a failed exchange.
  4. Read the user with an HTTP client that has short timeouts and follows no redirects. Turn any failure into keyring.NewSSOFailed(keyring.SSOUnavailable, ...), without the token in the message.
  5. Use the account's permanent ID as the Subject: one that never changes and is never reused.
  6. Pick one issuer for the provider, such as its website, and never change it.
  7. Set EmailVerified to true only when the provider's API says the address is verified, as a boolean.
  8. Answer false from SupportsReauthentication() and keyring.Never from Freshness().
  9. Test it with Laravel Go's HTTP client fake (httpclienttest), answering the token endpoint and the API with the bodies from the provider's docs.

CallbackQuery is the callback's 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 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.