我正在尝试为我的 React 应用程序实现身份验证,并且我创建了一个具有以下配置的 authConfig.ts 文件
import data from './config.json'
export const msalConfig = {
auth: {
clientId: data.clientId,
authority: `https://login.microsoftonline.com/${data.tenantId}`,
redirectUri: data.redirectUri
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level:any, message:string, containsPii:any) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
default:
return;
}
}
}
}
};
这工作正常,但它将 JSON 数据添加到 JS 文件中(基于我的另一个问题上的 answer)
所以我无法使用 JSON 文件的真正目的,即在构建后切换配置。
但基于这个很好的答案,我想我可以在运行时获取 JSON 文件值..(未尝试)
https://stackoverflow.com/a/75291195/954093
但我的挑战是如何在 authconfig.ts 文件中实现以下内容,因为它只是导出配置常量
useEffect(()=>{
fetch('settings.json').then(response => {
response.json().then(settings => {
// instead of setting state you can use it any other way
setState({settings: settings});
})
})
})
所以最终我需要客户端 ID、tenantID 等的 JSON 文件设置在运行时进入 authConfig.ts 文件,而不管构建时 config.json 文件中的内容如何。
最佳答案
创建一个钩子(Hook)以从json
加载数据
const useConfig = () => {
const [config, setConfig] = useState<any>();
useEffect(() => {
const loadAsync = async () => {
const sessionConfig = sessionStorage.getItem("config");
if (sessionConfig) {
setConfig(JSON.parse(sessionConfig));
return;
}
const response = await fetch("config.json");
const json = await response.json();
setConfig(json);
sessionStorage.setItem("config", JSON.stringify(json));
};
loadAsync();
}, []);
return [config];
};
export default useConfig;
将配置加载到MsalProvider
const MyProvider = (props: any) => {
const [config] = useConfig();
if (!config?.ui?.auth) return <>Loading config...</>;
// MSAL configuration
const configuration: Configuration = {
auth: config.ui.auth,
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
};
const pca = new PublicClientApplication(configuration);
return <MsalProvider instance={pca}>{props.children}</MsalProvider>;
};
最后:
<MyProvider>
<MsalAuthenticationTemplate interactionType={InteractionType.Redirect}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<MyApiProvider>
<App />
</MyApiProvider>
</LocalizationProvider>
</MsalAuthenticationTemplate>
</MyProvider>
关于reactjs - React 中 JSON 文件的 MSAL 动态配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75291266/