1当我点击注册时,它应该被重定向到http://localhost:7225/home。因为我已将其添加为 Azure 门户中的 Redirect URL。到这里为止似乎都很好,但仍然发现 localhost 没有发送任何数据。 ERR_EMPTY_RESPONSE [在此输入图像描述][2] 使用 MSAL.js
这是配置文件
import { PublicClientApplication, LogLevel } from "@azure/msal-browser";
export const b2cPolicies = {
names: {
signUpSignIn: "B2C_1_susi",
resetPassword: "B2C_1_Reset",
},
authorities: {
signUpSignIn: {
authority: "https://abc.b2clogin.com/xyz.onmicrosoft.com/B2C_1_susi",
}
},
};
export const msalConfig = {
auth: {
clientId: "00000000000000",
authority: b2cPolicies.authorities.signUpSignIn.authority,
knownAuthorities: ["xyz.b2clogin.com"],
redirectUri: "http://localhost:7225/home",
postLogoutRedirectUri: "https://localhost:7225/",
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
},
system: {
loggerOptions: {
loggerCallback: (level: any, message: any, containsPii: any) => {
if (containsPii) return;
switch (level) {
case LogLevel.Error:
console.error(`MSAL Error: ${message}`);
break;
case LogLevel.Warning:
console.warn(`MSAL Warning: ${message}`);
break;
case LogLevel.Info:
console.info(`MSAL Info: ${message}`);
break;
case LogLevel.Verbose:
console.debug(`MSAL Verbose: ${message}`);
break;
default:
console.log(`MSAL: ${message}`);
break;
}
},
piiLoggingEnabled: false,
logLevel: LogLevel.Verbose,
},
},
};
export const loginRequest = {
scopes: ["openid", "offline_access"],
};
export const msalInstance = new PublicClientApplication(msalConfig);
**索引.tsx
root.render(
<React.StrictMode>
<Provider store={store}>
<MsalProvider instance={msalInstance}>
<ApolloProvider client={graphqlclient}>
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>
</MsalProvider>
</Provider>
</React.StrictMode>
);
reportWebVitals();
**
**App.tsx(这是我从 Azure Ad b2c 调用登录页面的方式在此处输入图像描述)
useEffect(() => {
if (accounts.length === 0) {
msalInstance.loginRedirect({
scopes: ["openid"],
authority: b2cPolicies.authorities.signUpSignIn.authority,
redirectUri: "http://localhost:7225/home",
});
}
const callbackId = instance.addEventCallback((event:any) => {
if (
(event.eventType === EventType.LOGIN_SUCCESS || event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS) &&
event.payload?.account
) {
const account = event.payload.account;
instance.setActiveAccount(account);
}
if (event.eventType === EventType.LOGIN_FAILURE) {
if (event.error && event.error.errorMessage.includes('AADB2C90118')) {
const resetPasswordRequest = {
authority: b2cPolicies.authorities.resetPassword.authority,
scopes: [],
};
instance.loginRedirect(resetPasswordRequest);
}
}
});
return () => {
if (callbackId) {
instance.removeEventCallback(callbackId);
}
};
}, [instance]);
**
我创建了一个示例 React.js 应用程序,该应用程序使用 Azure Active Directory B2C 进行身份验证。
通过使用下面的代码,我可以毫无问题地登录并重定向到主页。
我的应用程序在端口:3000 上运行,因此我的重定向 URL 是
http:localhost:3000/home
。
App.tsx:
import React, { useEffect, useState } from "react";
import { useIsAuthenticated, useMsal } from "@azure/msal-react";
import { BrowserAuthError, EventType } from "@azure/msal-browser";
import { Route, Routes, useNavigate } from "react-router-dom";
import Home from "./components/Home";
import NavBar from "./components/NavBar";
import { loginRequest, b2cPolicies } from "./auth/b2cConfig";
const App: React.FC = () => {
const isAuthenticated = useIsAuthenticated();
const { instance, accounts } = useMsal();
const [isLoggingIn, setIsLoggingIn] = useState(false);
const navigate = useNavigate();
const handleLogin = async () => {
if (!isLoggingIn) {
setIsLoggingIn(true);
try {
await instance.loginRedirect({
scopes: loginRequest.scopes,
authority: b2cPolicies.authorities.signUpSignIn.authority,
redirectUri: "http://localhost:3000/home",
});
} catch (error) {
console.error("Login error:", error);
if (error instanceof BrowserAuthError && error.errorCode === "interaction_in_progress") {
console.warn("A login interaction is already in progress.");
}
} finally {
setIsLoggingIn(false);
}
}
};
useEffect(() => {
const callbackId = instance.addEventCallback((event: any) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload?.account) {
const account = event.payload.account;
instance.setActiveAccount(account);
navigate('/home');
window.history.replaceState({}, document.title, window.location.pathname);
}
if (event.eventType === EventType.LOGIN_FAILURE) {
if (event.error && event.error.errorMessage.includes('AADB2C90118')) {
const resetPasswordRequest = {
authority: b2cPolicies.authorities.resetPassword.authority,
scopes: [],
};
instance.loginRedirect(resetPasswordRequest);
}
}
});
return () => {
if (callbackId) {
instance.removeEventCallback(callbackId);
}
};
}, [instance, navigate]);
return (
<>
<NavBar handleLogin={handleLogin} isLoggingIn={isLoggingIn} />
<Routes>
<Route path="/" element={<h1>Welcome to the App!</h1>} />
<Route path="/home" element={isAuthenticated ? <Home /> : <h1>Please Log In</h1>} />
</Routes>
</>
);
};
export default App;
msal 配置:
import { PublicClientApplication, LogLevel } from "@azure/msal-browser";
export const b2cPolicies = {
names: {
signUpSignIn: "B2C_1_signUpSignIn",
resetPassword: "B2C_1_resetpassword",
},
authorities: {
signUpSignIn: {
authority: "https://<YourTeneantName>.b2clogin.com/<YourTeneantName>.onmicrosoft.com/B2C_1_signUpSignIn",
},
resetPassword: {
authority: "https://<YourTeneantName>.b2clogin.com/<YourTeneantName>.onmicrosoft.com/B2C_1_resetpassword",
},
},
};
export const msalConfig = {
auth: {
clientId: "<ClientId>",
authority: "https://<YourTeneantName>.b2clogin.com/kab2cappreg.onmicrosoft.com/B2C_1_signUpSignIn",
knownAuthorities: ["<YourTeneantName>.b2clogin.com"],
redirectUri: "http://localhost:3000/home",
postLogoutRedirectUri: "http://localhost:3000",
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false,
},
system: {
loggerOptions: {
loggerCallback: (level: LogLevel, message: string) => {
if (level === LogLevel.Error) console.error(message);
else if (level === LogLevel.Warning) console.warn(message);
else if (level === LogLevel.Info) console.info(message);
else console.debug(message);
},
piiLoggingEnabled: false,
logLevel: LogLevel.Verbose,
},
},
};
export const msalInstance = new PublicClientApplication(msalConfig);
export const loginRequest = {
scopes: ["openid", "offline_access"],
};
index.tsx:
import React from "react";
import ReactDOM from "react-dom/client";
import { MsalProvider } from "@azure/msal-react";
import { msalInstance } from "./auth/b2cConfig";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
const initializeMsal = async () => {
await msalInstance.initialize();
};
initializeMsal().then(() => {
root.render(
<React.StrictMode>
<MsalProvider instance={msalInstance}>
<BrowserRouter>
<App />
</BrowserRouter>
</MsalProvider>
</React.StrictMode>
);
}).catch(error => {
console.error("MSAL initialization failed", error);
});
reportWebVitals();
我在应用程序注册中将重定向URL设置为
http://localhost:3000
,如下所示。
输出:
登录成功后,跳转至首页。