auth

package
v1.0.31-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth signs people in with OAuth 2.0 and OpenID Connect: Google, Microsoft (Entra ID), Okta, Auth0, Keycloak, any identity provider, and through them SAML-backed company SSO. It runs the Authorization Code flow with PKCE (RFC 7636) the way native apps should (RFC 8252): in the system's browser or its in-app sign-in sheet, where the user's existing sessions and passkeys work, never in a web view the app controls.

sess := app.Auth(auth.Google("1234.apps.googleusercontent.com"))
tok, err := sess.SignIn(ctx)        // the browser, then back
...
tok, err = sess.Token(ctx)          // valid, refreshed when needed
client := sess.Client(ctx)          // an http.Client that sends it
sess.SignOut(ctx)

Tokens are kept in the platform's secure storage and survive restarts.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCanceled: the user closed the browser or sign-in sheet.
	ErrCanceled = errors.New("auth: sign-in canceled")
	// ErrSignedOut: there's no token; sign in first.
	ErrSignedOut = errors.New("auth: signed out")
	// ErrUnsupported: the platform has no native sign-in sheet, or no
	// passkeys.
	ErrUnsupported = errors.New("auth: not supported on this platform")
	// ErrNoPasskey: the device has no passkey for the site, or none of
	// the ones the server allows.
	ErrNoPasskey = errors.New("auth: no passkey for this account")
)

Errors a sign-in can end with.

Functions

This section is empty.

Types

type Claims

type Claims struct {
	Issuer        string   `json:"iss"`
	Subject       string   `json:"sub"`
	Audience      audience `json:"aud"`
	Email         string   `json:"email"`
	EmailVerified bool     `json:"email_verified"`
	Name          string   `json:"name"`
	Picture       string   `json:"picture"`
	Nonce         string   `json:"nonce"`
	Expiry        int64    `json:"exp"`
	// TenantID is Microsoft's directory; HostedDomain Google Workspace's.
	TenantID     string `json:"tid"`
	HostedDomain string `json:"hd"`
	// Raw has every claim.
	Raw map[string]any `json:"-"`
}

Claims are the usual claims of an OpenID Connect ID token: who signed in.

func ParseClaims

func ParseClaims(idToken string) (Claims, error)

ParseClaims reads an ID token's claims. It doesn't check the token's signature: the token came straight from the provider's token endpoint over TLS, which is what OpenID Connect allows a client to rely on; a server the app sends it to must verify it against the provider's keys.

type Error

type Error struct {
	Code        string `json:"error"`
	Description string `json:"error_description"`
}

Error is an OAuth error from the provider.

func (*Error) Error

func (e *Error) Error() string

type Host

type Host interface {
	// OpenBrowser opens u in the system's browser (an in-app browser tab
	// where the platform has one, as Custom Tabs on Android).
	OpenBrowser(ctx context.Context, u string) error
	// WaitForURL returns the next link opening the app that match takes,
	// keeping it from the app's own handler.
	WaitForURL(ctx context.Context, match func(*url.URL) bool) (*url.URL, error)
	// AuthSession runs the platform's sign-in sheet (ASWebAuthenticationSession
	// on iOS and macOS) on authURL until it's redirected to a URL of
	// callbackScheme, and returns that URL; ErrUnsupported elsewhere.
	AuthSession(ctx context.Context, authURL, callbackScheme string, ephemeral bool) (*url.URL, error)
	// Secrets are kept in secure storage under these.
	SecretGet(name string) ([]byte, error)
	SecretSet(name string, value []byte) error
	SecretDelete(name string) error
}

Host is what a session needs of the app: opening the browser, the links that come back to it, secure storage, and the platform's sign-in sheet. giode's App provides it (App.Auth).

type Provider

type Provider struct {
	// Name keys its stored tokens: "google", "work".
	Name string
	// The endpoints. Issuer alone is enough for OpenID Connect providers:
	// the rest are discovered from its .well-known/openid-configuration.
	Issuer        string
	AuthURL       string
	TokenURL      string
	RevokeURL     string
	EndSessionURL string
	// ClientID is the app's; ClientSecret only where the provider asks a
	// desktop app for one (Google does, though it isn't secret there).
	ClientID     string
	ClientSecret string
	// Scopes asked for; "openid email profile" by default for OpenID
	// Connect, with offline_access where the provider needs it to give a
	// refresh token.
	Scopes []string
	// RedirectURL is where the provider sends the user back:
	//   - empty on desktops: a loopback address on a free port
	//     (http://127.0.0.1:PORT/callback), registered with the provider
	//     as a loopback or "desktop" redirect;
	//   - a custom scheme ("com.example.app:/oauth") or an app link
	//     ("https://example.com/oauth") on phones, and on desktops that
	//     register one.
	RedirectURL string
	// Params are added to the authorization request: prompt,
	// login_hint, hd (Google Workspace domain), domain_hint.
	Params map[string]string
	// Ephemeral keeps iOS and macOS sign-in from sharing the browser's
	// cookies: no "signed in as" carried over, and nothing left behind.
	Ephemeral bool
}

Provider is an identity provider and the app's registration with it.

func Discover

func Discover(ctx context.Context, client *http.Client, p Provider) (Provider, error)

Discover fills p's missing endpoints from its issuer's .well-known/openid-configuration.

func Google

func Google(clientID string) Provider

Google is Google's OpenID Connect provider. Register an "iOS" client for phones (its redirect is the reversed client ID scheme, set here when RedirectURL is empty on a phone) or a "Desktop app" client for computers (a loopback redirect; Google gives desktop clients a secret that isn't secret: set ClientSecret).

func Microsoft

func Microsoft(tenant, clientID string) Provider

Microsoft is Microsoft's identity platform (Entra ID, formerly Azure AD): tenant is a directory ID or domain, "organizations" for any work account, "consumers" for personal ones, "common" for both. Register a "Mobile and desktop applications" platform with the redirect.

func OIDC

func OIDC(name, issuer, clientID string) Provider

OIDC is any OpenID Connect provider by its issuer URL (Okta, Auth0, Keycloak, a company's own): its endpoints are discovered on first use. SAML identity providers sign in through such a broker.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session signs in with one provider and keeps its token. Make one per provider (App.Auth) and keep it: it's safe to use from any goroutine.

func NewSession

func NewSession(host Host, p Provider) *Session

NewSession returns a session for p on host. Apps use App.Auth.

func (*Session) Client

func (s *Session) Client(ctx context.Context) *http.Client

Client returns an http.Client that sends the session's access token, refreshing it as it expires.

func (*Session) EndBrowserSession

func (s *Session) EndBrowserSession(ctx context.Context, idTokenHint string) error

EndBrowserSession opens the provider's sign-out page (OpenID Connect RP-initiated logout) in the browser, so the next sign-in asks for the account again. Call it after SignOut where the provider has one.

func (*Session) Provider

func (s *Session) Provider() Provider

Provider returns the session's provider, endpoints discovered.

func (*Session) Refresh

func (s *Session) Refresh(ctx context.Context) (Token, error)

Refresh gets a new access token with the refresh token.

func (*Session) SignIn

func (s *Session) SignIn(ctx context.Context) (Token, error)

SignIn runs the sign-in: the provider's page in the browser or the platform's sign-in sheet, back to the app, and the code exchanged for tokens, which it stores. ErrCanceled when the user backs out.

func (*Session) SignOut

func (s *Session) SignOut(ctx context.Context) error

SignOut revokes the tokens where the provider can, and forgets them. The browser may still be signed in to the provider (unless the session was Ephemeral); EndBrowserSession signs it out too.

func (*Session) SignedIn

func (s *Session) SignedIn() bool

SignedIn reports whether there's a token, stored or fresh (it may need a refresh: Token gets it).

func (*Session) Token

func (s *Session) Token(ctx context.Context) (Token, error)

Token returns a valid token: the stored one, refreshed when it's about to expire. ErrSignedOut when there's none, or the provider refused the refresh (the user signed out elsewhere, or revoked the app): sign in again.

func (*Session) WithHTTPClient

func (s *Session) WithHTTPClient(c *http.Client) *Session

WithHTTPClient sets the client token requests use. It returns s.

type Token

type Token struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type,omitempty"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	IDToken      string    `json:"id_token,omitempty"`
	Scope        string    `json:"scope,omitempty"`
	Expiry       time.Time `json:"expiry,omitempty"`
}

Token is what a sign-in gives.

func (Token) Claims

func (t Token) Claims() (Claims, error)

Claims returns the claims of the token's ID token.

func (Token) Valid

func (t Token) Valid() bool

Valid reports whether the access token is there and not about to expire (within a minute).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL