Created
October 19, 2018 23:49
-
-
Save AmaranthLIS/e83e950fa4a97149cdd126cecbbf9502 to your computer and use it in GitHub Desktop.
Golang, OpenID Connect auth code flow with Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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