javascript - 如何将 azure b2c 与 react 集成
问题描述
我正在使用 react 并且我必须通过我的用户登录Azure B2C
,所以我正在尝试这样做,但我无法找出如何做到这一点以及是什么。
我试过的
- 我从 Microsoft 网站获得了这个示例,该示例使用纯 JavaScript(香草)完成,我不知道如何在我的反应代码中实现它。
所以我尝试使用一些反应库,我四处搜索并找到了 这个库
我遵循了他们编写的相同代码,但是当我点击登录按钮时,它需要我进入天蓝色的登录页面,所以在我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 这很好,但在登录后它也只是抛出错误。
所以我无法解决这个问题,这就是为什么我搬到另一个几乎与此类似的库
所以在这里,当我点击登录按钮时,我收到错误消息
我从 Microsoft 获得的带有 valina Javascript 的示例,我认为这是完美的方法,但我如何通过反应来限制它,我不知道
我在这里呆了很长时间我不知道现在该怎么办,无法在谷歌上找到很好的例子来实现它
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://mylogin.b2clogin.com/tfp',
至
instance:'https://my-tanent-name.b2clogin.com/tenent-id/oauth2/authresp',
但我收到错误请求
我检查了网络选项卡,检查了它正在点击的网址,它正在点击下方
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
我认为这是错误的地方
解决方案
您的 b2c 实例坐标不正确(请参阅注释)。您可以找到更多详细信息:https ://docs.microsoft.com/en-us/azure/active-directory-b2c/b2clogin
如果你喜欢,你可以使用这个示例,它展示了如何使用oidc-client.js
库中的 React 应用程序中的 B2C 策略。默认情况下,它配置为使用 PKCE,但如果需要,您可以将其配置为使用隐式流(不推荐)。
git repo 中提供了完整的说明,但这里是高级概述。
- 您需要首先在 b2c 中创建应用程序以及策略(未显示)。您应该添加两个重定向 uri -
https://localhost:3000
和https://localhost:3000/callback.html
access_token
您还可以添加权限,以防您希望收到id_token
.
- 您的清单应类似于:
{
"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_id
哪个contoso
是租户名称。
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;
yarn
使用或构建并运行应用程序npm
应用程序将默认启动
http://localhost:3000
- 单击登录,它将带您进入 b2c 策略以完成旅程。
- 完成 b2c 策略中的旅程后,您将被重定向回应用程序。
推荐阅读
- c# - 如何在 VS 2017(WPF 应用程序)中创建和运行 ASM Dll?
- html - `backdrop-filter: blur()` 在 MacOS 上使用 Google-Chrome 会导致不需要的伪影
- python - 将 HTML 输入字符串提取到 Python 中
- swift - Swift AWSMobileClient getTokens 在 federatedSignIn 后不起作用
- excel - Excel 桌面,AzureAD 身份验证不起作用
- json - 从 SQL Server 检索数据并使用 python 将其转换为 JSON
- r - 根据另一列中的条件将值相加
- sql-server - SQL 让来自不同表的日期按列按时间顺序显示
- c - 如何解决“格式中的未知转换类型字符‘z’”编译器特定的警告?
- javascript - 与 Firebase 身份验证反应:如何设置持久性?