无法在使用 Azure B2C 访问受保护的 .NET Core API 的 React 应用程序中获取访问令牌

Cannot get access token in React app accessing protected .NET Core API with Azure B2C

我在尝试访问我自己的 .NET Core 3.1 网站时从我的 React 应用获取访问令牌时遇到问题 API。我可以正常登录并访问用户数据,但是当我尝试获取访问令牌时,我不断收到以下错误。将不胜感激任何帮助或推动正确的方向。谢谢!

Uncaught (in promise) BrowserAuthError: silent_sso_error: Silent SSO could not be completed - insufficient information was provided. Please provide either a loginHint or sid.

这是我的:

  1. 设置 React 应用程序注册(使用授权代码流重定向到 localhost:3000 的 SPA)
  2. 设置 .NET Core 网络 api 应用程序注册(网络重定向到 localhost:44347)
  3. 为网络创建了两个范围api(读和写)
  4. 授予 api spa 访问网络 api 范围的权限

.NET Core 3.1 Web API 设置(参考:https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration):

  1. 启动配置服务

services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAdB2C");

  1. appsettings.json
    "AzureAdB2C": {
       "Instance": "https://{example}.b2clogin.com",
       "ClientId": "{web api Client ID}",
       "TenantId": "xxxxxxxxxxxx",
       "Audience": "https://{example}.onmicrosoft.com/api"
    }

React 设置使用“@azure/msal-browser”:“^2.7.0”和“@azure/msal-react”:“^1.0.0-alpha.0”(参考:https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-react):

  1. index.tsx
const configuration: Configuration = {
  auth: {
      clientId: '{SPA Client ID}',
      authority: 'https://{example}.b2clogin.com/{example}.onmicrosoft.com/B2C_1_SignUpIn',
      knownAuthorities: ['{example}.b2clogin.com'],
  },
  cache: {
      cacheLocation: 'localStorage', // This configures where your cache will be stored
      storeAuthStateInCookie: false // Set this to "true" to save cache in cookies
  }
};

const pca = new PublicClientApplication(configuration);

<MsalProvider instance={pca}>
   <App />
</MsalProvider>
  1. App.tsx
  useEffect(() => {
    if (error) {
        login(InteractionType.Popup);
    }
  }, [error, login]);
  1. 获取令牌代码
const { instance, accounts, inProgress } = useMsal();

useEffect(() => {
        if (inProgress === 'none' && accounts.length > 0) {
            const request = {
                account: accounts[0],
                scopes: ["https://{example}.onmicrosoft.com/api/scope.read"]
            };
            // Retrieve an access token
            instance.acquireTokenSilent(request)
                .then(response => {
                    console.log('response', response);
                    if (response.accessToken) {
                        console.log('accessToken', response.accessToken);
                        return response.accessToken;
                    }
                    return null;
                })
                .catch(error => console.log('token error', error));
        }
    }, [inProgress, accounts, instance]);

您提到的文档都是关于 Azure AD 的,而不是 Azure AD B2C。

我们使用 react-azure-adb2c library to use ReactJS with Azure AD B2C. You could follow this blog,它向您展示了步骤和示例代码。

对于遇到类似问题的任何人,解决方法是在初始登录中传递具有范围的登录请求。就我而言,我正在使用 useMsalAuthentication() 挂钩登录。您可以关注此处的线程,https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/2702

export const loginRequest = {
    scopes: [ "openid", "https://{example}.onmicrosoft.com/api/scope.read" ]
}

const {login, error} = useMsalAuthentication(InteractionType.Redirect, loginRequest);