msal.js 2.0在loginRedirect后返回了空的tokenResponse

13

我正在开发一个Angular 10应用程序,利用Azure B2C进行策略和用户管理。我将我的应用程序注册在Azure Active Directory中,作为单页面应用程序,没有勾选隐式选项。我使用msal.js 2.0 @azure/msal-browser来登录B2C并使用代码流检索id和访问令牌。我设置了我的配置,创建了msal对象,定义了重定向承诺,然后稍后使用适当的用户范围调用loginRedirect。页面正确重定向。

然而,在我登录后,tokenResponse返回null。我尝试更改权限和范围,但它始终返回null。如何使handleRedirectPromise返回有效的令牌响应呢?

以下是我的代码:

    private msalConfig: Msal.Configuration = {
        auth: {
            clientId: xxxx-xx-xx-xx-xxxxx,
            authority: 'https://login.microsoftonline.com/common', 
            redirectUri: 'https://localhost:4200'
        },
        cache: {
            cacheLocation: 'sessionStorage',
            storeAuthStateInCookie: false
        },
    };

    private loginRequest: Msal.RedirectRequest = {
        scopes: ['user.read'],
    };

    const msalInstance = new Msal.PublicClientApplication(this.msalConfig);
    msalInstance
            .handleRedirectPromise()
            .then((tokenResponse: Msal.AuthenticationResult) => {
                let accountObj = null;
                if (tokenResponse !== null) {
                    accountObj = tokenResponse.account;
                    const id_token = tokenResponse.idToken;
                    const access_token = tokenResponse.accessToken;
                    console.log('id_token', id_token);
                    console.log('access_token', access_token);
                }
            })
            .catch(error => {
                authStore.loginError$.next(true);
                console.error(error);
            });

    msalInstance.loginRedirect(this.loginRequest);

编辑:

我也尝试过在msalConfig对象中使用authority: `https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>https://login.microsoftonline.com/tfp/{tenant}.onmicrosoft.com/B2C_1_SiupIn作为授权,以及在loginRequest中使用scopes: ['openid']。当我使用这个时,在尝试登录时会在浏览器中得到以下错误:

zone-evergreen.js:1068 GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https://<tenant>.b2clogin.com/<tenant>.onmicrosoft.com/b2c_1_defaultsigninsignup/oauth2/v2.0/authorize 400 (Bad Request)

core.js:4197 ERROR Error: Uncaught (in promise): ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.
ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.

在浏览器控制台中检查浏览器会话存储,以查看MSAL是否存在错误。 - Jas Suri - MSFT
该权限绝对不正确。应该采用以下格式:https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/<your-sign-in-sign-up-policy>。请参考示例https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp。 - Jas Suri - MSFT
AAD B2C 中不存在名为“user.read”的范围。请参阅此链接:https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-single-page-app-webapi?tabs=app-reg-ga - Jas Suri - MSFT
你所配置的是纯AAD流程,而不是AAD B2C。 - Jas Suri - MSFT
所以@Jas Suri,我尝试了作为一个权威,但是在浏览器中出现了错误(我在我的帖子中更新了完整的错误)。 我还检查了sessionStorage,并且它有'errors:["endpoints_resolution_error","endpoints_resolution_error"]'。 我也尝试过openid,<client-id>和一个空数组[]作为范围。 我已经寻找了使用msal 2.0的b2c示例,但很少找到。 我遵循了这个指南:https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/v1-migration.md?spm=a2c6h.14275010.0.0.146871f8rE1slq&file=v1-migration.md - afriedman111
该指南适用于AAD而非AAD B2C,请参考我提供的示例。 - Jas Suri - MSFT
2个回答

6
您设置的重定向流程方式似乎是正确的。您首先需要调用handleRedirectPromise() (注册它),然后再调用loginRedirect()。在页面加载时,handleRedirectPromise() 将返回 null,在登录后它应该返回令牌。
但是,您的配置存在问题。
  1. 您需要将您的域指定为knownAuthority,如:
        auth: {
            clientId: 'xxxx-xx-xx-xx-xxxxx',
            authority: 'https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>', 
            knownAuthorities: ['<your-tenant-name>.b2clogin.com']
            redirectUri: 'https://localhost:4200'
        },
  1. User.Read 是 MS Graph API 的范围。您不能在 B2C 中使用它。只允许使用 OIDC 范围,即请改用 openid

更多信息请参见 此处


谢谢!我取得了一些进展。我在我的msalConfig中添加了knownAuthorities条目。当我尝试登录时,不再出现错误。现在,我在我的sessionStorage中获取到了不同值的msal条目:params、origin、authority和nonce.id_token。然而,完整的重定向并没有发生。它似乎尝试着重定向,但又返回了。此外,tokenResponse仍然为空。 - afriedman111
不客气:)只是想确认一下,你是否也删除了'user.read'的范围并替换为'openid'? - derisen
是的,我使用了 { scopes: ['openid'] }。我在想这是否与我的应用程序注册有关? - afriedman111
1
我按照此处的Msal 2.0注册 https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-app-registration#redirect-uri-msaljs-20-with-auth-code-flow - afriedman111
1
奇怪..可能与浏览器有关。您是否有一个公共存储库,我可以查看一下?或者,您可以通过电子邮件将网络跟踪发送给我(我建议使用Fiddler)。此外,还有一个Angular 10示例可供AAD检查 https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-angular-v2-samples/angular10-browser-sample - derisen
显示剩余4条评论

4
问题出在我的Angular应用上。我让应用将基本URL重定向到我的“/home”路由。因此,每当您打开基本路由时,应用都会进行重定向。从该路由发出请求。我在我的AAD应用注册中添加了对“/home”路由的重定向URI,注释掉了我的b2c配置中的redirectUri并将navigateToLoginRequestUrl设置为true。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接