有一些方法可以使用 Go 获取访问令牌。
1.使用 Http 请求
以authorization code flow为例,整个代码示例here:
func GetTokens(c AuthorizationConfig, authCode AuthorizationCode, scope string) (t Tokens, err error) {
formVals := url.Values{}
formVals.Set("code", authCode.Value)
formVals.Set("grant_type", "authorization_code")
formVals.Set("redirect_uri", c.RedirectURL())
formVals.Set("scope", scope)
if c.ClientSecret != "" {
formVals.Set("client_secret", c.ClientSecret)
}
formVals.Set("client_id", c.ClientID)
response, err := http.PostForm(TokenURL, formVals)
if err != nil {
return t, errors.Wrap(err, "error while trying to get tokens")
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return t, errors.Wrap(err, "error while trying to read token json body")
}
err = json.Unmarshal(body, &t)
if err != nil {
return t, errors.Wrap(err, "error while trying to parse token json body")
}
return
}
2。使用MSAL Go
// 1.1 Initializing a public client:
publicClientapp, err := public.New("client_id", public.WithAuthority("https://login.microsoftonline.com/Enter_The_Tenant_Name_Here"))
// 1.2 Initializing a confidential client:
confidentialClientApp, err := confidential.New("client_id", cred, confidential.WithAuthority("https://login.microsoftonline.com/Enter_The_Tenant_Name_Here"))
// 2. MSAL comes packaged with an in-memory cache. Utilizing the cache is optional, but we would highly recommend it.
var userAccount public.Account
accounts := publicClientApp.Accounts()
if len(accounts) > 0 {
// Assuming the user wanted the first account
userAccount = accounts[0]
// found a cached account, now see if an applicable token has been cached
result, err := publicClientApp.AcquireTokenSilent(context.Background(), []string{"your_scope"}, public.WithSilentAccount(userAccount))
accessToken := result.AccessToken
}
// 3. If there is no suitable token in the cache, or you choose to skip this step, now we can send a request to AAD to obtain a token.
result, err := publicClientApp.AcquireToken"ByOneofTheActualMethods"([]string{"your_scope"}, ...(other parameters depending on the function))
if err != nil {
log.Fatal(err)
}
accessToken := result.AccessToken
最后,Azure SDK for Go 似乎用于向 Azure 进行身份验证,但它不提供获取访问令牌的 SDK 方法。