【问题标题】:How to acquire OAuth2.0 token from Azure AD in Go?如何在 Go 中从 Azure AD 获取 OAuth2.0 令牌?
【发布时间】:2021-04-24 21:23:51
【问题描述】:

我正在尝试使用 Go 使用 Azure 服务总线实体。通过提供 SAS 令牌或 Azure AD OAuth2.0 令牌,可以使用 Azure 服务总线进行身份验证,这将通过 Azure AD 应用程序的安全主体获得。从技术上讲,我更喜欢安全主体选项而不是 SAS 令牌,因为它存在安全漏洞。

如何使用没有 Azure AD SDK 的 Go 从 Azure AD 获取 OAuth2.0 令牌?

是否可以直接调用 Azure AD REST API 来访问 OAuth2.0 令牌?

【问题讨论】:

  • 你见过this吗?

标签: go azure-servicebus-topics


【解决方案1】:

有一些方法可以使用 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 方法。

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2019-05-15
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 2020-01-14
    • 2016-08-15
    相关资源
    最近更新 更多