我正试图使用Go使用Azure服务总线实体。通过提供SAS令牌或Azure AD OAuth2.0令牌,可以使用Azure服务总线进行身份验证,这些令牌将通过Azure AD应用程序的安全主体获得。从技术上讲,我更喜欢安全主体选项,而不是SAS令牌,因为它有安全漏洞。
如何使用Go从Azure AD获取OAuth2.0令牌,而Azure AD SDK不可用?
是否可以直接调用Azure AD REST API来访问OAuth2.0令牌?
有一些方法可以使用Go获取访问令牌。
1.使用Http请求
例如,对于授权代码流,这里的整个代码示例:
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方法。