package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/davecgh/go-spew/spew"
)
type UserInfo struct {
Subject string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
FamilyName string `json:"family_name"`
GivenName string `json:"given_name"`
PreferredUsername string `json:"preferred_username"`
}
func main() {
token := "ey...paste your token here"
discoveryURL := "https://localhost:8080/auth/realms/testrealm/.well-known/openid-configuration"
userInfo := getUserInfo(token, discoveryURL)
spew.Dump(userInfo)
}
func getUserInfo(token, discoveryURL string) *UserInfo {
rsp, e := http.Get(discoveryURL)
if e != nil {
log.Println("getUserInfo: could not connect to oidc idp", e.Error())
return nil
}
rspbody := make(map[string]interface{})
dec := json.NewDecoder(rsp.Body)
if e := dec.Decode(&rspbody); e != nil {
log.Println("getUserInfo: decode oidc response body", e.Error())
return nil
}
uie := rspbody["userinfo_endpoint"].(string)
client := http.DefaultClient
uireq, e := http.NewRequest(http.MethodGet, uie, nil)
if e != nil {
log.Println("getUserInfo: NewRequest error", e.Error())
return nil
}
uireq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
uirsp, e := client.Do(uireq)
if e != nil {
log.Println("getUserInfo: could not connect to oidc userinfo endpoint", e.Error())
return nil
}
userinfo := new(UserInfo)
uidec := json.NewDecoder(uirsp.Body)
if e := uidec.Decode(userinfo); e != nil {
log.Println("getUserInfo: could not connect decode userinfo endpoint response body", e.Error())
return nil
}
return userinfo
}