Skip to content

Instantly share code, notes, and snippets.

@int128 int128/main.go
Created Mar 19, 2018

Embed
What would you like to do?
OpenID Connect auth code flow with Go
package main
import (
"crypto/rand"
"encoding/binary"
"fmt"
"github.com/coreos/go-oidc"
"golang.org/x/oauth2"
)
type IDTokenClaim struct {
Email string `json:"email"`
}
func main() {
provider, err := oidc.NewProvider(oauth2.NoContext, "https://keycloak.example.com/auth/realms/hello")
if err != nil {
panic(err)
}
config := oauth2.Config{
ClientID: "****",
ClientSecret: "****",
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "email"},
}
var stateSeed uint64
binary.Read(rand.Reader, binary.LittleEndian, &stateSeed)
state := fmt.Sprintf("%x", stateSeed)
authCodeURL := config.AuthCodeURL(state)
fmt.Printf("Open %s\n", authCodeURL)
fmt.Println()
fmt.Printf("Enter authorization code: ")
var code string
if _, err := fmt.Scanln(&code); err != nil {
panic(err)
}
fmt.Println()
fmt.Printf("You entered code: \"%s\"\n", code)
token, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
panic(err)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
panic("id_token is missing")
}
verifier := provider.Verifier(&oidc.Config{ClientID: config.ClientID})
idToken, err := verifier.Verify(oauth2.NoContext, rawIDToken)
if err != nil {
panic(err)
}
idTokenClaim := IDTokenClaim{}
if err := idToken.Claims(&idTokenClaim); err != nil {
panic(err)
}
fmt.Printf("You are %s (%s)", idTokenClaim.Email, idToken.Subject)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.