【问题标题】:Bearer token works with ADAL, does not work with MSAL不记名令牌适用于 ADAL,不适用于 MSAL
【发布时间】:2020-11-05 10:59:22
【问题描述】:

我想访问一个正在运行的受保护 Web API。在 Azure 中,应用注册是:

  • 具有对 Web API 的租户管理员权限的 SPA
  • Web API 没有租户管理员权限,因此为其 id 请求令牌将返回“应用程序需要访问资源的权限”错误

我正在尝试获取 Web API 的不记名令牌。问题是它不适用于 MSAL,但它确实适用于 ADAL。

这是我的“SPA”的 ADAL vanilla JS 代码:

window.config = {
   clientId: 'SPA client id',
   tenant: 'Tenant id',
   redirectUri: 'http://localhost:3000',
   extraQueryParameter: 'nux=1',
   popUp: true
};


var authContext = new AuthenticationContext(config);

function getToken(){
    var user = authContext.getCachedUser();
    if (!user) {
        authContext.login();
        return;
    }
    var cachedToken = authContext.getCachedToken(window.config.endpoints.prod);
    if (!cachedToken) {
        authContext.acquireToken("Web API Client Id", function(error, token) {
            console.log(error);
        });
    }
    console.log(cachedToken);
    var t = document.getElementById("token");
    t.innerText = cachedToken;
};

如果我在 Postman 中复制令牌并发出请求,它将起作用。

MSAL代码如下:

const msalConfig = {
      auth: {
                clientId: "SPA client id",
                authority: "https://login.microsoftonline.com/Tenant id"
            }
        };

const loginRequest = {
       scopes: ["copied the scope of SPA from the Expose API"],
       redirectUri: "http://localhost:3000/"
};
 const myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.loginPopup(loginRequest).then(handleResponse).catch(function (error) { console.log(error);});
var tokenRequest = {
             scopes: ["Copied scope from the Web API expose API section"],
            };
            if (!token) {
                myMSALObj.acquireTokenPopup(tokenRequest)
                    .then(response => {
                        console.log(response);
                        setTimeout(function () { 
                        token = response.accessToken;
                    });
    console.log(token);

现在我注意到有一点不同:ADAL 允许我在调用 acquireToken 方法时传递 Web Api 的客户端 ID,而 MSAL 不允许。找不到任何文档,但我认为它是从 Application Id Uri 解决的。

第二个区别在于令牌声明 aud:

  • ADAL aud 是 Web API 客户端 ID
  • MSAL aud 是 Web API 应用程序 ID Uri

【问题讨论】:

  • MSAL报错是什么?我试试the sample,效果很好。
  • 感谢您试用。当我在范围 [] 中使用 AppId/范围并且应用注册具有 AppIdUri/范围形式的范围时,MSAL 似乎有效。我不知道为什么 AppIdUri 不起作用,但我认为 API 被配置为只接受它自己的 App Id 而不是它的 App Id Uri。为什么它的范围(在公开 API 部分)是这样写的?我不知道。

标签: azure azure-active-directory


【解决方案1】:

应用程序有两个标识符,AppId 形式为 xxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxx 和AppIdURI,由用户提供。

如果我使用范围 xxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxx\user.read 它可以工作。我以AppIdURI\user.read 的形式使用范围。因此,除了 aud 之外,令牌是相同的,其中 ADAL 具有客户端 ID(也称为 App Id),而 MSAL 具有 AppIdURI。改成 AppId 就可以了。

我不知道为什么该应用不接受 AppIdUri,因为在 Expose an API 部分中,范围写为 AppIdUri/user.read

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 2021-11-08
    • 1970-01-01
    • 2018-11-09
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多