Skip to content

Instantly share code, notes, and snippets.

@anjankow
Last active July 4, 2022 19:57
Show Gist options
  • Save anjankow/79a1845c21f322437a03c3eda9170f9d to your computer and use it in GitHub Desktop.
Save anjankow/79a1845c21f322437a03c3eda9170f9d to your computer and use it in GitHub Desktop.
Getting custom Azure AD B2C user attributes
/*****
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
*****/
// The user attributes we are interested in should be given in the path.
// The custom attributes include B2C extension app ID in their name.
path := "https://graph.microsoft.com/v1.0/" + tenantID + "/users/" + userID +
"?$select=userPrincipalName," +
"extension_" + extensionID + "_PrivateKey," +
"extension_" + extensionID + "_PublicKey"
r, err := http.NewRequestWithContext(ctx, http.MethodGet, path, nil)
if err != nil {
panic(err)
}
// make sure to use a valid token
r.Header.Add("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(r)
if err != nil {
panic(err)
}
defer resp.Body.Close()
reponseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
if !isResponseSuccess(resp.StatusCode) {
if resp.StatusCode == http.StatusUnauthorized {
// if unauthorized, normally you would request a new token and try again
panic(err)
}
panic("status code: " + resp.Status + "; error details: " + string(responseBody))
}
// Now we want to read the response using the json library
// but if we know the extensions app ID only in the runtime,
// we can't use it in the struct tag as we normally would do.
// That's why first we want to remove the extensions app ID from the response.
modifiedBody := strings.ReplaceAll(string(reponseBody), "extension_" + extensionID + "_", "")
// Finally we can parse the response using the known attribute names.
var unmarshalled struct {
Name string `json:"userPrincipalName"`
PrivateKey string `json:"PrivateKey"`
PublicKey string `json:"PublicKey"`
}
if err := json.Unmarshal([]byte(modifiedBody), &unmarshalled); err != nil {
panic(err)
}
fmt.Println(unmarshalled.PublicKey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment