如何将Azure B2C与React集成

12

我正在使用React,并且必须通过 Azure B2C 为我的用户提供登录,因此我尝试实现此功能,但我无法找到如何实现以及是什么的方法。

我尝试过的

  1. 我从Microsoft网站上得到了这个示例,它使用纯JavaScript(vanilla)完成,我不知道如何在我的React代码中实现它。

所以我尝试使用一些React库,Google了一下并找到了这个库

我遵循了他们编写的相同代码,但是当我点击登录按钮时,它会将我带到Azure的登录页面。因此,在我的app.js中,我在登录后执行console.log(authentication.getAccessToken());,但它返回null,我不知道为什么

我的代码

authentication.initialize({
        // optional, will default to this
        instance: 'https://login.microsoftonline.com/tfp',
        // My B2C tenant
        tenant: 'mytenant.onmicrosoft.com',
        // the policy to use to sign in, can also be a sign up or sign in policy
        signInPolicy: 'B2c_signupsignin',
        // the the B2C application you want to authenticate with (that's just a random GUID - get yours from the portal)
        clientId: 'fdfsds5-5222-ss522-a659-ada22',
        // where MSAL will store state - localStorage or sessionStorage
        cacheLocation: 'sessionStorage',
        // the scopes you want included in the access token
        scopes: ['https://mytenant.onmicrosoft.com/api/test.read'],
        // optional, the redirect URI - if not specified MSAL will pick up the location from window.href
        redirectUri: 'http://localhost:3000',
    });

然后在点击登录按钮时,我正在执行这个操作。

const Log_in = () => {
        authentication.run(() => {});
        
    };

在我的 app.js 文件中,我像下面这样做:

import authentication from 'react-azure-b2c';

function App() {
    console.log(authentication.getAccessToken());   
}

一开始显示null是可以的,但是在登录后仍然会出现错误。

我无法解决这个问题,因此转向了另一个类似的库

  1. 这个库

在这里,当我点击登录按钮时,我会得到以下错误

Error

我从Microsoft获得的示例使用原始JavaScript,我认为这是完美的方法,但我不知道如何在React中实现它

这是使用纯JS的代码

我已经被卡在这里很长时间了,现在不知道该怎么办,在谷歌上找不到好的例子来在React中实现它

PS: 我正在使用React hooks函数组件编写我的代码,请指导我

我只想以正确的方式使用React实现这一点,我知道有很多人已经在使用它,所以我想看到一个很好的例子。

编辑/更新

我尝试这样做

    b2cauth.initialize({
    instance: 'https://mylogin.b2clogin.com/tfp',
    tenant: 'mylogin.b2clogin.com',
    signInPolicy: 'B2C_1_SigninSignupUsername',
    clientId: 'fc3081ec-504a-4be3-a659-951a9408e248',
    cacheLocation: 'sessionStorage',
    scopes: ['https://mylogin.b2clogin.com/api/demo.read'],
    redirectUri: 'http://localhost:3000',
});
b2cauth.run(() => {
    ReactDOM.render(<App />, document.getElementById('root'));
    serviceWorker.unregister();
});

我查看了作为答案粘贴的Microsoft链接,并更改了实例:

instance:'https://my-tanent-name.b2clogin.com/tenent-id/oauth2/authresp',

但是我收到了错误请求的错误信息。

我检查了网络选项卡和访问的URL, 它正在打以下URL:

https://login.microsoftonline.com/common/discovery/instance?api-version=1.0&authorization_endpoint=https://my-tenatnt-name.b2clogin.com/tenant-id/oauth2/authrespmy-tenant-name.b2clogin.com/b2c_1_signinsignupusername/oauth2/v2.0/authorize

我尝试将实例中的 https 移除,并像这样访问:

//mytenant.b2clogin.com/tenant-id/oauth2/authresp

它会抛出错误:Uncaught AuthorityUriInsecure

Error

我认为它去了错误的地方。


我的回答被管理员删除了,所以评论中,您不需要创建任何按钮,当用户点击您的网站URL时,它将被重定向到Microsoft b2c页面,他们的用户将输入他们的详细信息。成功登录后,它将被重定向回您的应用程序,这个重定向配置将在您在门户注册应用程序时发生。 - Manish
但是我认为你可以通过在门户中添加http://localhost:3001来解决这个CORS问题。 - Manish
请查看此链接 https://learn.microsoft.com/en-us/samples/azure-samples/active-directory-b2c-javascript-msal-singlepageapp/active-directory-b2c-javascript-msal-singlepageapp/ - Manish
@Manish,是的,我已经尝试过了,但不起作用。上述库不好,因为它很久以前就停止更新了,如果出现问题,没有人能提供帮助。 - manish thakur
@AlexAIT 我尝试了那个方法,但还是卡住了,你能帮我一下吗? - manish thakur
显示剩余2条评论
1个回答

6

您的 b2c 实例坐标不正确(请查看说明)。您可以在https://learn.microsoft.com/en-us/azure/active-directory-b2c/b2clogin找到更多详细信息。

如果您愿意,您可以使用这个示例,展示了如何使用 oidc-client.js 库从 React 应用程序中使用 B2C 策略。默认情况下,它被配置为使用 PKCE,但如果需要的话(不推荐),可以将其配置为使用隐式流。

完整的说明提供在 git 存储库中,但这是一个高级概述:

  • 您需要首先在 b2c 中创建应用程序和策略(未显示)。您应该添加两个重定向 URI -- https://localhost:3000https://localhost:3000/callback.html

enter image description here

  • 如果您想要接收一个 access_token 以外的 id_token,您还可以添加权限。

enter image description here

  • 您的清单应该类似于:
{
    "id": "443ca8db-7bd1-4ebd-9671-ce94e006a18a",
    "acceptMappedClaims": null,
    "accessTokenAcceptedVersion": 2,
    "addIns": [],
    "allowPublicClient": null,
    "appId": "50d2c416-a5ad-4c5c-b36a-0d1ac5b48167",
    "appRoles": [],
    "oauth2AllowUrlPathMatching": false,
    "createdDateTime": "2020-09-02T00:11:35Z",
    "groupMembershipClaims": null,
    "identifierUris": [],
    "informationalUrls": {
        "termsOfService": null,
        "support": null,
        "privacy": null,
        "marketing": null
    },
    "keyCredentials": [],
    "knownClientApplications": [],
    "logoUrl": null,
    "logoutUrl": null,
    "name": "OIDC-Test-APP",
    "oauth2AllowIdTokenImplicitFlow": false,
    "oauth2AllowImplicitFlow": false,
    "oauth2Permissions": [],
    "oauth2RequirePostResponse": false,
    "optionalClaims": null,
    "orgRestrictions": [],
    "parentalControlSettings": {
        "countriesBlockedForMinors": [],
        "legalAgeGroupRule": "Allow"
    },
    "passwordCredentials": [],
    "preAuthorizedApplications": [],
    "publisherDomain": "contoso.onmicrosoft.com",
    "replyUrlsWithType": [
        {
            "url": "http://localhost:3000/signin-callback.html",
            "type": "Spa"
        },
        {
            "url": "http://localhost:3000/",
            "type": "Spa"
        }
    ],
    "requiredResourceAccess": [
        {
            "resourceAppId": "00000003-0000-0000-c000-000000000000",
            "resourceAccess": [
                {
                    "id": "37f7f235-527c-4136-accd-4a02d197296e",
                    "type": "Scope"
                },
                {
                    "id": "7427e0e9-2fba-42fe-b0c0-848c9e6a8182",
                    "type": "Scope"
                }
            ]
        },
        {
            "resourceAppId": "18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85",
            "resourceAccess": [
                {
                    "id": "d5515006-5646-4398-ad59-fffc357f3423",
                    "type": "Scope"
                }
            ]
        }
    ],
    "samlMetadataUrl": null,
    "signInUrl": null,
    "signInAudience": "AzureADandPersonalMicrosoftAccount",
    "tags": [],
    "tokenEncryptionKeyId": null
}
  • 克隆repo并更新AuthSettings.ts中的设置,以匹配您的租户。您必须更新client_idcontoso,即租户名称。
const settings = {

      // This is  the metadata endpoint
      authority: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_signup_signin',
      
      // Turn off calls to user info since CORS will block it
      loadUserInfo: false, 

      // The URL where the Web UI receives the login result
      redirect_uri: 'http://localhost:3000/signin-callback.html',

      // The no longer recommended implicit flow must be used if CORS is disabled
      // If you want to use impicit flow use id_token instead of code for the return type.
      response_type: 'code',

      // Other OAuth settings
      client_id: '18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85',
      
      // openid is required, remove https://contoso.onmicrosoft.com/test/Read if access_token is not required.
      scope: 'openid https://contoso.onmicrosoft.com/test/Read', 
       // Supply these details explicitly. Directly copied from azure ad b2c policy metadata endpoint.
       metadata: {
        issuer: 'https://contoso.b2clogin.com/9859cd0c-9d99-4683-abcc-87462f67a0bc/v2.0/',
        authorization_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1a_signup_signin',
        token_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1a_signup_signin',
        jwks_uri : 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1a_signup_signin',
        end_session_endpoint: "https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?p=b2c_1a_signup_signin&post_logout_redirect_uri=http%3A%2F%2Flocalhost:3000%2F"

    },

  } as UserManagerSettings;
  • 使用 yarnnpm 构建并运行该应用程序。

  • 默认情况下,该应用程序将在 http://localhost:3000 上启动。

enter image description here

  • 单击登录,然后它应该带您到 b2c 策略以完成旅程。

enter image description here

  • 在 b2c 策略中完成旅程后,您将被重定向回应用程序。

enter image description here


那么,tfp 不是必需的吗? - manish thakur
Manish,我已经添加了一个工作配置文件到我的答案中,供您与您的条目进行比较。目前,从您的条目中无法确定您正在使用哪种OIDC流程,但如果您能分享一下这个信息就很有帮助了。根据我的配置文件,我正在使用OIDC implicit流程。 - Razi
我可以分享,但是您正在定义的“stsSettings”是否也需要我定义,如果需要,在哪里定义?我正在使用https://www.npmjs.com/package/react-azure-adb2c这个库。 - manish thakur
Manish -- 我实际上已经使用 oidc-client.js 和 b2c 在 react 中编写了一个工作示例。如果您不介意使用该库,我可以将其作为我的答案的一部分分享给您,以便您可以基本上使用它。 - Razi
我已经添加了详细信息和指向有效示例的链接。 - Razi

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