Last active
July 4, 2022 19:24
-
-
Save anjankow/61bcfcf02dac24864bcd72d7aab7d7a5 to your computer and use it in GitHub Desktop.
Getting an access token from Azure AD B2C using client's secret
This file contains 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
/* | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
"strings" | |
) | |
*/ | |
path := "https://login.microsoftonline.com/" + tenantID + "/oauth2/v2.0/token" | |
data := url.Values{} | |
data.Set("client_id", clientID) | |
data.Set("client_secret", secret) | |
data.Set("scope", "https://graph.microsoft.com/.default") | |
data.Set("grant_type", "client_credentials") | |
r, err := http.NewRequest(http.MethodGet, path, strings.NewReader(data.Encode())) | |
if err != nil { | |
panic(err.Error()) | |
} | |
r.Header.Add("Content-Type", "application/x-www-form-urlencoded") | |
resp, err := http.DefaultClient.Do(r) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
responseBody, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
panic(err) | |
} | |
if resp.StatusCode != http.StatusOK { | |
panic("status code: " + resp.Status + "; error details: " + string(responseBody)) | |
} | |
var unmarshalled struct { | |
Token string `json:"access_token"` | |
} | |
if err := json.Unmarshal(responseBody, &unmarshalled); err != nil { | |
panic(err) | |
} | |
fmt.Println(unmarshalled.Token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment