我正在使用React,并且必须通过 Azure B2C
为我的用户提供登录,因此我尝试实现此功能,但我无法找到如何实现以及是什么的方法。
我尝试过的
- 我从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是可以的,但是在登录后仍然会出现错误。
我无法解决这个问题,因此转向了另一个类似的库
在这里,当我点击登录按钮时,我会得到以下错误
我从Microsoft获得的示例使用原始JavaScript,我认为这是完美的方法,但我不知道如何在React中实现它
我已经被卡在这里很长时间了,现在不知道该怎么办,在谷歌上找不到好的例子来在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
我认为它去了错误的地方。