You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang集成Azure AD时InteractiveBrowserCredential获取Token失败

Golang 实现Azure AD认证无法获取令牌问题

问题表现

使用Golang对接Azure AD实现认证逻辑时,授权流程可正常触发,但令牌获取环节失败,抛出如下错误:

InteractiveBrowserCredentiall authentication failed
响应内容:Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests.

复现代码

package main

import (
"context"
"fmt"

"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azi "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {

cred, err := azi.NewInteractiveBrowserCredential(&azi.InteractiveBrowserCredentialOptions{
    TenantID:    "<Tenant-id>",
    ClientID:    "<Client id>",
    RedirectURL: "http://localhost:3000/auth/",
})
if err != nil {
    fmt.Println(err.Error())
    return
}

fmt.Println("No error 😎")
var ctx = context.Background()
policy := policy.TokenRequestOptions{Scopes: []string{"User.Read"}}
fmt.Println(cred.GetToken(ctx, policy))
}

故障原因

你在Azure AD应用注册后台,将当前ClientID对应的应用平台配置为了单页应用程序(SPA)。Azure AD对SPA类型客户端有强制限制:该类客户端签发的令牌仅允许通过跨域请求完成兑换。而你使用的InteractiveBrowserCredential属于公共客户端(桌面程序、后端服务场景)认证组件,发起的令牌兑换请求不符合SPA的跨域要求,因此被服务端拒绝。

解决方法

根据你的实际业务场景二选一即可:

  • 如果是写Go后端/桌面端工具:登录Azure AD后台进入对应应用注册页,打开「身份验证」配置栏,新增移动和桌面应用程序平台,将代码中配置的重定向地址http://localhost:3000/auth/添加到该平台的重定向URL列表中,删除之前配置在SPA平台下的同一条重定向地址,保存配置后重新运行代码即可正常获取令牌。
  • 如果是要给前端单页应用做认证:不要在Go后端用azidentity组件走交互式浏览器认证流程,改用前端侧的MSAL.js SDK实现认证逻辑,匹配SPA的跨域令牌兑换规则。

内容的提问来源于stack exchange,提问作者omkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 12:54:18