【问题标题】:How can i check if the token passed to a POST command is authorized?如何检查传递给 POST 命令的令牌是否被授权?
【发布时间】:2021-03-02 09:10:21
【问题描述】:

我的应用程序使用 MSAL v2.0 在 angular 8 中。 该应用程序要求用户提供 Office 365 凭据,将其登录,然后允许他们在日历中创建事件。 用户已成功登录,获取了令牌,但尝试使用 MS Graph Rest API 在日历中创建事件时,系统会抛出 401 Unauthorized 错误。

下面的登录函数在用户登录时返回登录成功消息。accessToken 值为空,但 idToken 有值。 accessToken 应该有值吗?另外,是因为 loginPopup 命令中需要范围而出现 401 错误吗?:

loginPopup(request) {
        return super.loginPopup(request)
            .then((authResponse) => 
            this.broadcastService.broadcast("msal:loginSuccess", authResponse);
            return authResponse;
        })
            .catch((error) => {
            this.broadcastService.broadcast("msal:loginFailure", error);
            this.getLogger().error("Error during login:\n" + error.errorMessage);
            throw error;
        });
    }

错误信息是: zone-evergreen.js:1042 "POST https://graph.microsoft.com/v1.0/me/events 401 (未授权)"

单击此错误消息中的链接https://graph.microsoft.com/v1.0/me/events 显示: https://login.microsoftonline.com//oauth2/v2.0/authorize?response_type=id_token&scope=openid%20profile&client_id=&redirect_uri=https%3A%2F%2FmyApp.abc.com%2F&state=%3D&nonce=ad9d4ce5-7676-5515-a36c-7b2b3c70d366&client_info=1& -client-SKU=MSAL.JS&x-client-Ver=1.4.2&login_hint=sales1%40abc.com&client-request-id=&response_mode=fragment&sso_reload=true

【问题讨论】:

  • 能否分享失败请求的requestid、时间戳和整个错误响应?
  • 您需要访问令牌才能调用 Microsoft Graph。使用msal.js的方法请看:docs.microsoft.com/en-us/azure/active-directory/develop/….
  • 如果我的回答对您有帮助,您可以接受它作为答案(单击答案旁边的复选标记,将其从灰色切换为已填充。)。这对其他社区成员可能是有益的。谢谢你:)

标签: angular microsoft-graph-api unauthorized


【解决方案1】:

这是因为您只是发送登录请求,而不是请求获取访问令牌。你的response_type=id_token,所以你只获得了一个id token。

调用这个api需要你有访问令牌,因为你调用的是/me端点,所以你需要obtain a user token interactively

const requestObj = {
      scopes: ["user.read"]
  };

  this.authService.acquireTokenPopup(requestObj).then(function (tokenResponse) {
      // Callback code here
      console.log(tokenResponse.accessToken);
  }).catch(function (error) {
      console.log(error);
  });

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 2017-06-27
    • 1970-01-01
    • 2019-07-27
    • 2016-11-09
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多