在 Angular 项目中使用 MSAL 集成 SSO 登录后返回 401 错误

问题描述 投票:0回答:1

我完全遵循 MSAL Git 的 Angular 16 示例中的示例。除了客户端ID和权限之外,代码与示例完全相同。当我使用我的帐户登录时,我收到 401 错误响应。我也不知道如何解码 URL 中的加密代码。是否因为我的帐户无权访问 Azure AD 中的应用程序,如何解码 URL? URL 类似于 localhost:5069/api#code=xxx&client_info=xxx&state=xxx&session_state=xxx,包含 4 个部分,codeclient_infostatesession_state。我如何从他们那里提取信息?

401 error

azure-active-directory single-sign-on msal-angular
1个回答
0
投票

如果未向 Microsoft Entra ID 应用程序授予执行操作所需的 API 权限,通常会出现 401 错误。

我创建了一个多租户 Microsoft Entra ID 应用程序

enter image description here

注册重定向网址:

enter image description here

在调用 User.Read

 端点时授予 
/me
 委派 API 权限:

enter image description here

现在在环境文件中替换您的客户端ID:

export const environment = {
    production: false,
    msalConfig: {
        auth: {
            clientId: 'YourClientID',
            authority: 'https://login.microsoftonline.com/common'
        }
    },
    apiConfig: {
        scopes: ['user.read'],
        uri: 'https://graph.microsoft.com/v1.0/me'
    }
};

enter image description here

当我运行示例时,我使用弹出窗口进行登录:

enter image description here

用户登录成功:

enter image description here

能够成功获取登录的用户个人资料数据:

enter image description here

要解决该错误,请确保向 Microsoft Entra ID 应用程序授予所需的 API 权限。

如果问题仍然存在,请检查您是否传递了有效的 ClientID。

  • 并确保在环境文件中传递正确或所需的范围。
  • 如果您正在调用任何其他 API,则授予并传递所需的范围。

参考:

开发人员的 microsoft-authentication-library-for-js/samples/msal-angular-v3-samples/angular16-sample-app · AzureAD/microsoft-authentication-library-for-js · GitHub

© www.soinside.com 2019 - 2024. All rights reserved.