I have created a web application in azure and tried to configure sso using MSAL react library. But while clicking on the sso button it is redirecting and within seconds it is coming back to the login page.
I have created the following files:
Authconfig.js
export const msalConfig = {auth: {clientId: "client-id",authority: "``https://login.microsoftonline.com/tenant-id``",redirectUri: "``http://localhost:5173/home``",},cache: {cacheLocation: "sessionStorage", // Use sessionStorage to avoid localStorage issuesstoreAuthStateInCookie: false,},};
LoginButon.js
import React from 'react';import { useMsal } from "@azure/msal-react";
const LoginButton = () => {const { instance } = useMsal();
const handleLogin = () => {instance.loginPopup().catch(e => {console.error(e);});};
return (<button onClick={handleLogin} style={styles.button}>Sign in with SSO</button>);};
const styles = {button: {padding: "10px 20px",backgroundColor: "#0078d4",color: "white",border: "none",borderRadius: "5px",cursor: "pointer",},};
export default LoginButton;
App.js
import React from 'react';import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';import LoginButton from './components/LoginButton';import Home from './components/Home';
function App() {return (<Router><Routes><Route path="/" element={<LoginButton />} /><Route path="/home" element={<Home />} /></Routes></Router>);}
export default App;
index.js
// src/index.jsimport React from 'react';import ReactDOM from 'react-dom';import App from './App';import { PublicClientApplication } from "@azure/msal-browser";import { MsalProvider } from "@azure/msal-react";import { msalConfig } from './authConfig';
// src/index.jsconst msalInstance = new PublicClientApplication(msalConfig);
msalInstance.handleRedirectPromise().then(response => {if (response) {console.log('User successfully logged in');}}).catch(err => {console.error(err);});
ReactDOM.render(<MsalProvider instance={msalInstance}><App /></MsalProvider>,document.getElementById('root'));
Home.js
// src/pages/Home.jsimport React from 'react';
const Home = () => {return (<div>
export default Home;
After clicking on SSO button it needs to validate the user and needs to redirect to Home.js pageAzure:
I have configured http://localhost:5173/home
as redirectUri in azure . Also i have added the scopes openid,email and profile
2
Answers
The Error your facing is because of misconfiguration of redirect URL in Azure App Registration.
The Redirect URL defined in authConfig and Azure App Registration URL Should be same as shown below.
Azure App Registration -> Authentication ->Single-Page application -> Add URI -> Save.
authConfig.js:
Below Is complete code for to configure sso using MSAL react library.
LoginButton:
index.js:
App.js:
Home.js:
After Successfully running, I got below page.
Output: