skip to Main Content

I am currently working on a calendar application which needs a login/user authentication. I tried doing it using azure, but due to my lack of expertise in Azure I found myself lost in multiple tutorials. I need the solution of this one. Any help or leads would be really helpful.
Here is how my application looks like.

Index.js

ReactDOM.render(
  <React.StrictMode>
    <ContextWrapper>
      <App />
    </ContextWrapper>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js

return (
      <Router>
        <Routes>
          <Route exact path="/" element = {
            <React.Fragment>
              <div className="overall">
                <CalendarHeader />
                <div className="main-content-area">
                  <Sidebar />
                  <Month month={currentMonth} />
                  <EventModal />
                </div>
              </div>
            </React.Fragment>
            }>
          </Route>
          <Route exact path="/addEvents" element={<UpdateEventsForms />}></Route>
          <Route exact path="/editdeletedata" element={<EditAndDelete />}></Route>
          <Route exact path="/adminPage" element={<AdminPage />}></Route>
        </Routes>
      </Router>
  );

Header.js

<div>
 <button className="button-calendar-today">Sign-In</button>
 <button className="button-calendar-today" onClick={() => navigate("/adminPage")}>Admin 
 Login</button>
</div> 

And how I want is like when the user is not logged-in then don’t want to display admin page instead I would like to show sign-in button. But when the user is logged-in I want to display the admin page not the sign-in button.
Moreover, when clicked on Admin login that will take the user to the Admin Page (<AdminPage />) which is user in my react-router above in App.js

2

Answers


  1. Chosen as BEST ANSWER
    import React, { useState, useContext, useEffect } from "react";
    import "./App.css";
    import { BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom';
    import { getMonth } from "./util";
    import CalendarHeader from "./components/CalendarHeader/CalendarHeader";
    import Sidebar from "./components/SideBar/Sidebar";
    import Month from "./components/Month/Month";
    import GlobalContext from "./Context/GlobalContext";
    import EventModal from "./components/EventModal/EventModal";
    import UpdateEventsForms from "../src/components/AdminPage/UpdateEventsForm/UpdateEventsForm";
    import EditAndDelete from "../src/components/AdminPage/EditAndDelete/EditAndDelete";
    import AdminPage from "./components/AdminPage/AdminPage";
    import { MsalProvider, AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from '@azure/msal-react';
    import { PublicClientApplication } from '@azure/msal-browser';
    import msalConfig from '../src/components/CalendarHeader/msalConfig/msalConfig'
    
    
    const msalInstance = new PublicClientApplication(msalConfig);
    
    function App() {
      const [currentMonth, setCurrentMonth] = useState(getMonth());
      const { monthIndex} = useContext(GlobalContext);
      const { accounts } = useMsal();
      const [user, setUser] = useState(null);
      useEffect(() => {
         const account = accounts[0];
        setUser(account);
      }, [accounts]);
    
      useEffect(() => {
        setCurrentMonth(getMonth(monthIndex));
      }, [monthIndex]);
    
      return (
        <Router>
          <MsalProvider instance={msalInstance}>
            <Routes>
              <Route exact path="/" element = {
                <React.Fragment>
                  <div className="overall">
                    <CalendarHeader />
                    <div className="main-content-area">
                      <Sidebar />
                      <Month month={currentMonth} />
                      <EventModal />
                    </div>
                  </div>
                </React.Fragment>
                }>
              </Route>
              <Route exact path="/adminPage" element={<AdminPage />}></Route>
              <Route exact path="/addEvents" element={<UpdateEventsForms />}></Route>
              <Route exact path="/editdeletedata" element={<EditAndDelete />}></Route>
            </Routes>
            <AuthenticatedTemplate>
              <Navigate to='/adminPage'/>
            </AuthenticatedTemplate>
            <UnauthenticatedTemplate>
              <Navigate to='/'/>
            </UnauthenticatedTemplate>
          </MsalProvider> 
        </Router>
      );
    }
     
    export default App;
    

    I did this, but getting this error. Please let me know what am I missing here?

    invalid_request: 9002326 - [2024-04-10 06:33:49Z]: AADSTS9002326: Cross-origin token redemption is permitted only for the 'Single-Page Application' client-type. Request origin: 'http://localhost:3000'. Trace ID: b7bcd3b9-adef-4248-b5ef-82fc43b8e800 Correlation ID: 7bda3ab6-93a8-49f9-b5ef-ada5f03cdd00 Timestamp: 2024-04-10 06:33:49Z - Correlation ID: 7bda3ab6-93a8-49f9-b5ef-ada5f03cdd00 - Trace ID: b7bcd3b9-adef-4248-b5ef-82fc43b8e800
    ServerError: invalid_request: 9002326 - [2024-04-10 06:33:49Z]: AADSTS9002326: Cross-origin token redemption is permitted only for the 'Single-Page Application' client-type. Request origin: 'http://localhost:3000'. Trace ID: b7bcd3b9-adef-4248-b5ef-82fc43b8e800 Correlation ID: 7bda3ab6-93a8-49f9-b5ef-ada5f03cdd00 Timestamp: 2024-04-10 06:33:49Z - Correlation ID: 7bda3ab6-93a8-49f9-b5ef-ada5f03cdd00 - Trace ID: b7bcd3b9-adef-4248-b5ef-82fc43b8e800
        at ResponseHandler.validateTokenResponse (http://localhost:3000/static/js/bundle.js:110706:27)
        at AuthorizationCodeClient.acquireToken (http://localhost:3000/static/js/bundle.js:107101:21)
        at async InteractionHandler.handleCodeResponseFromServer (http://localhost:3000/static/js/bundle.js:101901:27)
        at async PopupClient.acquireTokenPopupAsync (http://localhost:3000/static/js/bundle.js:100552:22)
    

  2. I tried the following React.js code for login/user authentication with Azure Active Directory.

    Code :

    AdminPage.js :

    import React from 'react';
    const AdminPage = () => {
      return (
        <div>
          <h1>Admin Page</h1>
          {/* Add your admin page content here */}
        </div>
      );
    };
    export default AdminPage;
    

    Home.js :

    import React from 'react';
    const Home = () => {
      return (
        <div>
          <h1>Home Page</h1>
          {/* Add your home page content here */}
        </div>
      );
    };
    export default Home;
    

    SignInButton.js :

    import React from 'react';
    import { useMsal } from '@azure/msal-react';
    const SignInButton = () => {
      const { instance } = useMsal();
      const handleLogin = () => {
        instance.loginPopup();
      };
      return <button onClick={handleLogin}>Sign In</button>;
    };
    export default SignInButton;
    

    msalConfig.js :

    export const msalConfig = {
        auth: {
          clientId: '<client_ID>',
          authority: 'https://login.microsoftonline.com/<tenant_ID>',
          redirectUri: 'http://localhost:3000',
        },
      }; 
    

    App.js :

    import React, { useState, useEffect } from 'react';
    import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
    import { MsalProvider, AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from '@azure/msal-react';
    import { PublicClientApplication } from '@azure/msal-browser';
    import { msalConfig } from './msalConfig';
    import AdminPage from './components/AdminPage';
    import Home from './components/Home';
    import SignInButton from './components/SignInButton';
    
    const msalInstance = new PublicClientApplication(msalConfig);
    
    function App() {
      const { accounts } = useMsal();
      const [user, setUser] = useState(null);
      useEffect(() => {
         const account = accounts[0];
        setUser(account);
      }, [accounts]);
    
      return (
        <Router>
          <MsalProvider instance={msalInstance}>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/adminPage" element={<AdminPage />} />
            </Routes>
            <AuthenticatedTemplate>
              <Navigate to="/adminPage" />
            </AuthenticatedTemplate>
            <UnauthenticatedTemplate>
              <SignInButton />
            </UnauthenticatedTemplate>
          </MsalProvider>
        </Router>
      );
    }
    
    export default App;
    

    I added the output URL below in the Azure AD app’s Authentication as a Single-page application.

    http://localhost:3000
    

    enter image description here

    Output :

    The React application below ran successfully.

    enter image description here

    I received the output below in the browser. Then, I clicked on Sign In and selected my credentials for signing in as shown below.

    enter image description here

    I successfully signed in and got the Admin Page as below.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search