Skip to content

Instantly share code, notes, and snippets.

@aufi
Last active May 27, 2022 11:36
Show Gist options
  • Save aufi/57556376c440301713bde6b04b57ca4a to your computer and use it in GitHub Desktop.
Save aufi/57556376c440301713bde6b04b57ca4a to your computer and use it in GitHub Desktop.
Keycloak userInfo test queries
$ export TOKEN="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSl..."
$ curl -v -H "Authorization: Bearer $TOKEN" 'https://tackle-konveyor-tackle.apps.cluster-mauf.local/auth/realms/tackle/protocol/openid-connect/userinfo'
{"sub":"7749cf8a-bb8a-43c7-a689-80c90e6023eb","email_verified":false,"preferred_username":"admin"}
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
// response:
//{"sub":"7749cf8a-bb8a-43c7-a689-80c90e6023eb","email_verified":false,"preferred_username":"admin"}
type UserInfo struct {
Username string `json:"preferred_username"`
}
func main() {
url := "https://tackle-konveyor-tackle.apps.cluster-mauf.local"
token := "Bearer eyJhbGciOiJSUzI1NiIsInRsVzgWK5f7n1LSvjg..."
log.Print(getDirectUserInfo(url, "tackle", token))
}
func getDirectUserInfo(host, realm, token string) (username string, err error) {
// Prepare request to the Keycloak endpoint
req, err := http.NewRequest("GET", fmt.Sprintf("%s/auth/realms/%s/protocol/openid-connect/userinfo", host, realm), nil)
if err != nil {
log.Println("ERROR getDirectUserInfo new", err)
return
}
// Set auth header and allow ssl verification errors
req.Header.Add("Authorization", token)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// Send the request
resp, err := client.Do(req)
if err != nil {
log.Println("ERROR getDirectUserInfo req", err)
return
}
defer resp.Body.Close()
// Parse response
body, err := ioutil.ReadAll(resp.Body)
if err != nil || resp.StatusCode >= 300 {
log.Println("ERROR getDirectUserInfo resp", err, resp.StatusCode)
return
}
// Prepare username
var userInfo UserInfo
err = json.Unmarshal(body, &userInfo)
if err != nil {
log.Println("ERROR getDirectUserInfo parsing", err)
return
}
username = userInfo.Username
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment