Skip to content
Sign-in with OIDC and OAuth

Sign-in with OIDC and OAuth

The auth package signs a user in through their identity provider. On a desktop it uses the browser they already use. On iOS and Android it uses the platform’s own sign-in for Apple and Google (see On phones). It returns the user’s name, email and tokens. The widget.AuthButton wraps the whole flow in a branded button.

The flow is OAuth 2.0 Authorization Code with PKCE (a one-time secret that proves the app that started the sign-in is the one finishing it). It is the flow intended for desktop apps. On a desktop the package opens the system browser and listens on a local port.

Add a sign-in button

signIn := widget.NewAuthButton("google", googleClientID, func(r auth.OIDCResult) {
	// Runs on the UI thread, so it can update widgets directly.
	status.SetText("Signed in as " + r.Name + " (" + r.Email + ")")
})
signIn.OnError = func(err error) {
	status.SetText("Sign-in failed: " + err.Error())
}

NewAuthButton takes a provider key, the client ID your provider gave you, and a function to call once the user is signed in. When the user taps the button:

  1. The default browser opens the provider’s sign-in page.
  2. The user signs in there.
  3. The provider sends the browser back to the app, and the app finishes the sign-in in the background.
  4. Your function runs on the UI thread with an auth.OIDCResult. It can update widgets directly.

If the sign-in fails, OnError runs instead, also on the UI thread. A tap while a sign-in is already in progress is ignored. A disabled button does not stop a sign-in that is already running.

The button draws the provider’s logo and brand colors. Set Text or Logo to override them. Scopes is a space-separated list, for example "openid email profile", and Issuer sets the provider address when the key needs one (see below).

Providers

KeyProviderWhat you set
googleGoogleClient ID
microsoftMicrosoft (Entra ID), multi-tenant endpointClient ID
appleAppleClient ID
githubGitHub (OAuth 2.0, not OpenID Connect)Client ID, and scopes (see below)
oktaOktaClient ID and Issuer, your Okta address
keycloakKeycloakClient ID and Issuer, your realm address
any other key, such as customany OpenID Connect providerClient ID and Issuer

The logos, colors and default labels live in auth.Providers. Keycloak has no logo there. An unknown key gets a grey button labelled “Sign in”.

What you register with the provider

Create an app registration (often called a “client”) of the native, desktop or public kind. Then check three things:

  • Redirect URI. The app listens on http://127.0.0.1:<port>/callback, and the operating system picks a free port for each sign-in. The provider must accept a loopback redirect on any port.
  • No client secret. The app sends only the client ID and the PKCE verifier when it exchanges the code for tokens. A registration that requires a client secret will reject the exchange.
  • Scopes. OpenID Connect providers get openid email profile unless you set others.

The client ID is not a secret. It is fine to compile it into the app.

How the sign-in is checked

For every provider, including GitHub, the package sends a random state value with the request and rejects a reply that does not return it.

For every provider except GitHub, the package also:

  • reads the provider’s discovery document from <issuer>/.well-known/openid-configuration, and rejects it if the issuer inside does not match the one you asked for;
  • verifies the ID token’s signature against the provider’s published keys, and checks its issuer, audience (your client ID), expiry and nonce.

The browser shows a short “Authentication Successful” page that tells the user to return to the app. The whole flow times out after five minutes.

GitHub

GitHub uses plain OAuth 2.0, so there is no ID token to verify. After the code exchange the package asks the GitHub API for the user. In the result, Sub is the numeric GitHub user ID, and Name falls back to the login when the user has no display name. Of the three token fields, only AccessToken is set: GitHub sign-ins have no refresh token and no ID token.

With no Scopes set, GitHub is asked for user:email read:user. (Before v1.1.0 it was sent the OpenID Connect defaults instead.)

Without the button

Call auth.Authenticate when you want your own UI. It blocks until the sign-in finishes, fails or times out, so run it in a goroutine and come back to the UI thread with bellui.Do:

sso := widget.NewButton("Sign in with company SSO", func() {
	go func() { // Authenticate blocks until the browser flow ends.
		r, err := auth.Authenticate(auth.OIDCConfig{
			Provider: "okta",
			Issuer:   "https://example.okta.com",
			ClientID: "0oa-example-client-id",
		})
		bellui.Do(func() { // Back on the UI thread.
			if err != nil {
				status.SetText("Sign-in failed: " + err.Error())
				return
			}
			status.SetText("Signed in as " + r.Email)
		})
	}()
})

auth.OIDCConfig also has Scopes (a slice) and Timeout (five minutes when zero). Nonce sets the nonce sent with the request, which the ID token must carry. Set it when your server issued the nonce and checks the token against it, so a captured token cannot be used for another request. Left empty, the package makes a random one and checks it itself.

On phones

On iOS and Android there is no loopback redirect the providers accept, so Authenticate and the button use the platform’s own sign-in instead:

ProviderPlatformWhat it showsClientID
appleiOSthe Sign in with Apple sheetoptional: without one, the token’s audience must be the app’s bundle ID
googleAndroidCredential Manageryour Web client ID
googleiOSGoogle’s sign-in page in an ASWebAuthenticationSessionyour iOS client ID

Every other provider returns an error on phones. The ID token is checked as on a desktop: its signature against the provider’s published keys, then its issuer, audience, expiry and nonce.

apple := widget.NewButton("Sign in with Apple", func() {
	go func() {
		// On iOS this shows the Sign in with Apple sheet. With no
		// ClientID, the token must be for the app's bundle ID.
		r, err := auth.Authenticate(auth.OIDCConfig{Provider: "apple"})
		bellui.Do(func() {
			switch {
			case errors.Is(err, auth.ErrCancelled):
				status.SetText("Sign-in cancelled")
			case err != nil:
				status.SetText("Sign-in failed: " + err.Error())
			default:
				// Send r.AuthorizationCode to your server, which
				// redeems it with Apple for a refresh token.
				status.SetText("Signed in as " + r.Email)
			}
		})
	}()
})

When the user closes the sheet without signing in, Authenticate returns auth.ErrCancelled. Test for it with errors.Is. A button passes it to OnError. The desktop flow cannot see the browser tab close, so it never returns ErrCancelled.

Each flow needs something from the app:

  • Sign in with Apple needs the com.apple.developer.applesignin entitlement. Put it in ios/Entitlements.plist next to your code; bellui package adds it when it signs the app (see Mobile):

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    	<key>com.apple.developer.applesignin</key>
    	<array>
    		<string>Default</string>
    	</array>
    </dict>
    </plist>

    The sheet gives no access or refresh token. Instead, OIDCResult.AuthorizationCode holds a one-time code that your server redeems with Apple for the user’s refresh token. Apple gives the user’s name only on the first sign-in.

  • Google on Android needs the Credential Manager libraries in android/libs: androidx.credentials:credentials, androidx.credentials:credentials-play-services-auth and com.google.android.libraries.identity.googleid:googleid, with all their dependencies. bellui package does not download them; see Mobile.

  • Google on iOS redirects to the reversed client ID, the com.googleusercontent.apps.<id> scheme of your iOS client ID.

Remembering the user

The button saves the refresh token when the provider returns one. You can read it back at the next launch:

// A refresh token saved by an earlier sign-in, if any.
if refresh, email, err := auth.LoadToken("google"); err != nil {
	log.Println("could not read stored token:", err)
} else if refresh != "" {
	status.SetText("Previously signed in as " + email)
}

LoadToken returns empty strings, not an error, when nothing is stored. If you call Authenticate yourself, store the token with SaveToken.

To sign out, remove the token:

signOut := widget.NewButton("Sign out", func() {
	signIn.CancelAuth()
	if err := auth.ClearToken("google"); err != nil {
		log.Println("could not clear token:", err)
	}
	status.SetText("Not signed in")
})

Tokens are stored per app, under its unique ID, so the app must be created with app.NewWithID (or have an ID in its manifest). Without one, every token function returns ErrNoAppID.

Several issuers under one provider

LoadToken, SaveToken and ClearToken keep one token per provider name. For a provider whose issuer you choose, such as two Keycloak realms or two Okta tenants under one name, use SaveTokenFor, LoadTokenFor and ClearTokenFor, which take the issuer as well, so each issuer keeps its own token. An empty issuer, or the provider preset’s own, is the same as no issuer. (New in v1.2.0. Before, the second realm’s sign-in replaced the first’s token.)

The button saves this way, with its Issuer. A button on a preset issuer (Google, Apple, GitHub, Microsoft’s common endpoint) saves the provider’s token, as in the example above. A button whose Issuer differs from its preset’s, which is every “okta”, “keycloak” and “custom” button and a “microsoft” button set to one tenant, saves a token that only LoadTokenFor finds and only ClearTokenFor removes. Read and clear it with the same provider and issuer as the button, or a sign-out leaves the token on disk.

How the token is stored:

  • It is encrypted with AES-256-GCM in a file named <provider>.enc, in a folder named after the app’s ID, inside a bellui-auth folder under the user’s config directory (the one Go’s os.UserConfigDir returns). A token for one issuer goes in an issuers folder beside it, under a hashed name.
  • Two apps that sign in with the same provider keep separate tokens, and the app ID is part of the encryption key, so one app cannot read another’s token.
  • The encryption key comes from a secret kept in the operating system’s secret store: the Keychain on macOS, DPAPI on Windows, and the Secret Service (through the secret-tool command) on Linux.
  • With no secret store available, for example on a headless Linux machine, the secret is a random file in the same folder, readable only by the user.
  • A new token is written beside the old one and then renamed over it, so an app killed in the middle of a save keeps the token it had.
  • Token files do not work on another machine. A file that cannot be decrypted is deleted, and the user simply signs in again.
  • Versions before v1.1.0 kept one token per provider for all apps, directly in bellui-auth. Those tokens are not read any more, so users sign in once more after upgrading. From v1.2.0, the old file for a provider (bellui-auth/<provider>.enc) is deleted the first time any app saves or clears a token for that provider.
The package does not use the refresh token for you. It stores it and gives it back. Exchanging it for a new access token is up to your app.

Gotchas

  • The app needs an ID. Tokens are kept per app, so app.New() without an ID in the manifest makes every token call fail with ErrNoAppID. Use app.NewWithID.
  • CancelAuth only stops the button. The button stops waiting and reports nothing. The local listener keeps waiting for the browser until the five-minute timeout.
  • The user must finish in the browser. Nothing in the app window changes while the browser page is open. Show a hint such as “Continue in your browser” if the wait could confuse people.