页面刷新后 React MSAL 不起作用
我在应用程序中使用 @azure/msal-react 和 @azure/msal-browser 进行身份验证。到目前为止,我已经初始化了一个 msal 实例并使用它来获取令牌并获取别名。一切正常,直到我进行页面刷新,我想了解这是否是缓存问题,我看到有关 msal 的本地存储中存在数据,但在活动帐户中仍然为空。
在这里您可以看到带有配置的 msal 实例(authProvider) AuthProvider.js
import * as APIConstants from "./Common/APIConstants";
import {
BrowserCacheLocation,
PublicClientApplication,
LogLevel
} from '@azure/msal-browser';
const loggerCallback = (logLevel, message) => {
console.log(message);
};
const configuration = {
auth: {
authority: APIConstants.TENANT,
clientId: APIConstants.CLIENT_ID,
postLogoutRedirectUri: window.location.origin,
redirectUri: window.location.origin,
validateAuthority: true,
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: BrowserCacheLocation.localStorage,
storeAuthStateInCookie: true,
},
system: {
loggerOptions: {
loggerCallback,
logLevel: LogLevel.Info,
piiLoggingEnabled: false
}
}
};
export const authProvider = new PublicClientApplication(configuration);
Login.js
import React, { Component } from "react";
import { authProvider } from "../../authProvider";
import * as APIConstants from "../../Common/APIConstants";
import {
EventType,
} from '@azure/msal-browser';
class Login extends Component {
constructor() {
super()
this.successEventId = null;
}
loginSuccessCallback = (event) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload;
const account = payload.account;
authProvider.setActiveAccount(account);
this.props.history.push("/dashboard");
}
}
componentDidMount = () => {
this.successEventId = authProvider.addEventCallback(this.loginSuccessCallback);
}
componentWillUnmount = () => {
if (this.successEventId)
authProvider.removeEventCallback(this.successEventId);
}
onLDAPLogin = () => {
authProvider.loginRedirect({
scopes: [APIConstants.RESOURCE_URI],
})
}
render() {
return (
< div >
<button onClick={() => this.onLDAPLogin()}>LDAP Login</button>
</div>
);
}
}
export default Login;
Dashboard.js
目的dashboard.js 是通过api 调用收集数据,您可以使用该用户的别名和令牌进行调用
const getAllData = async () => {
let user = await Services.getLogedInUser();
if (user) {
let username = user.username;
let alias = username.split("@")[0];
let token = await Services.getAccessToken();
if (token) {
await initiateApiCall(alias,token);
} else {
props.history.push("/");
}
}
else {
props.history.push("/");
}
}
Services.js
export const getAccessToken = async () => {
const activeAccount = authProvider.getActiveAccount();
const accounts = authProvider.getAllAccounts();
if (!activeAccount && accounts.length === 0) {
/*
* User is not signed in. Throw error or wait for user to login.
* Do not attempt to log a user in outside of the context of MsalProvider
*/
}
const request = {
scopes: [APIConstants.RESOURCE_URI],
account: activeAccount || accounts[0]
};
const authResult = await authProvider.acquireTokenSilent(request);
console.log('auth result acquire token ', authResult);
return authResult.accessToken
};
export const getLogedInUser = async () => {
console.log('authProvider', authProvider);
console.log('all accounts ', authProvider.getAllAccounts());
let account = authProvider.getActiveAccount();
console.log('account ', account);
return account;
};
正如控制台中所示,我同时获得活动帐户和所有帐户帐户值,但如果我刷新页面,活动帐户为空,所有帐户都是空数组
I am using @azure/msal-react and @azure/msal-browser for authentication in our application. So far i have intialized a msal instance and used it to acquire a token and fetch the alias. Everything works until i do a page refresh i want to understand if this is a cache issue i see data is present in local storage regarding msal but still getting null in active account.
here you can see the msal instance with configuration (authProvider)
AuthProvider.js
import * as APIConstants from "./Common/APIConstants";
import {
BrowserCacheLocation,
PublicClientApplication,
LogLevel
} from '@azure/msal-browser';
const loggerCallback = (logLevel, message) => {
console.log(message);
};
const configuration = {
auth: {
authority: APIConstants.TENANT,
clientId: APIConstants.CLIENT_ID,
postLogoutRedirectUri: window.location.origin,
redirectUri: window.location.origin,
validateAuthority: true,
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: BrowserCacheLocation.localStorage,
storeAuthStateInCookie: true,
},
system: {
loggerOptions: {
loggerCallback,
logLevel: LogLevel.Info,
piiLoggingEnabled: false
}
}
};
export const authProvider = new PublicClientApplication(configuration);
Login.js
import React, { Component } from "react";
import { authProvider } from "../../authProvider";
import * as APIConstants from "../../Common/APIConstants";
import {
EventType,
} from '@azure/msal-browser';
class Login extends Component {
constructor() {
super()
this.successEventId = null;
}
loginSuccessCallback = (event) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload;
const account = payload.account;
authProvider.setActiveAccount(account);
this.props.history.push("/dashboard");
}
}
componentDidMount = () => {
this.successEventId = authProvider.addEventCallback(this.loginSuccessCallback);
}
componentWillUnmount = () => {
if (this.successEventId)
authProvider.removeEventCallback(this.successEventId);
}
onLDAPLogin = () => {
authProvider.loginRedirect({
scopes: [APIConstants.RESOURCE_URI],
})
}
render() {
return (
< div >
<button onClick={() => this.onLDAPLogin()}>LDAP Login</button>
</div>
);
}
}
export default Login;
dashboard.js
purpose dashboard.js is to collect data through api call where you use alias and token of that user to make the call
const getAllData = async () => {
let user = await Services.getLogedInUser();
if (user) {
let username = user.username;
let alias = username.split("@")[0];
let token = await Services.getAccessToken();
if (token) {
await initiateApiCall(alias,token);
} else {
props.history.push("/");
}
}
else {
props.history.push("/");
}
}
Services.js
export const getAccessToken = async () => {
const activeAccount = authProvider.getActiveAccount();
const accounts = authProvider.getAllAccounts();
if (!activeAccount && accounts.length === 0) {
/*
* User is not signed in. Throw error or wait for user to login.
* Do not attempt to log a user in outside of the context of MsalProvider
*/
}
const request = {
scopes: [APIConstants.RESOURCE_URI],
account: activeAccount || accounts[0]
};
const authResult = await authProvider.acquireTokenSilent(request);
console.log('auth result acquire token ', authResult);
return authResult.accessToken
};
export const getLogedInUser = async () => {
console.log('authProvider', authProvider);
console.log('all accounts ', authProvider.getAllAccounts());
let account = authProvider.getActiveAccount();
console.log('account ', account);
return account;
};
As it is shown in the console i get both active account and all accounts value but in case i refresh the page active account is null and all accounts is an empty array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论