Search code examples
reactjsazure-active-directoryazure-ad-msalmsal-react

Using MSAL.js to integrate React Single-page applications with Azure Active Directory


I'm learning about authentication on React application using MSAL and I was following this: https://www.youtube.com/watch?v=7oPSL5wWeS0

I created an application in Microsoft tenant

and made the code updates:

index.tsx

import { PublicClientApplication } from '@azure/msal-browser';


export const pca = new PublicClientApplication({
  auth: {
    clientId: 'clientId',
    authority: 'https://login.microsoftonline.com/tenantId',
    redirectUri: '/'
  }
});

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
    <App/>
);

App.tsx

import { SignInButton } from './components/SignInButton';
import { MsalProvider} from "@azure/msal-react";
import { pca } from "./index";


function App() {
  
  return (
    <MsalProvider instance={pca}>
      <SignInButton />      
    </MsalProvider>
  );
}

export default App;

SignInButton.tsx

import { DefaultButton } from '@fluentui/react/lib/Button';
import { useMsal } from "@azure/msal-react";

export const SignInButton = () => {
    const { instance } = useMsal();

    const handleSignIn = () => {
        instance.loginRedirect({
            scopes: ['user.read']
        });
    }

    return (
        <DefaultButton onClick={handleSignIn}>Sign in</DefaultButton>
    )
};

and on running the app, I see this error immediately after I click on 'SignIn' button:

enter image description here

What am I missing?

enter image description here


Solution

  • I tried to reproduce the same in my environment and got results as below:

    I registered one Azure AD application(SPA) and added redirect URI as http://localhost:3000 like this:

    enter image description here

    Now I cloned same msal-react sample and modified code as below:

    App.js

    import Grid from "@mui/material/Grid";
    import { PageLayout } from "./components/PageLayout";
    import { Routes, Route } from "react-router-dom";
    
    import { Home } from "./pages/Home";
    import { Profile } from "./pages/Profile";
    
    import { MsalProvider } from "@azure/msal-react";
    
    
    function App({msalInstance}) {
        return (
            <MsalProvider instance = {msalInstance}>
            <PageLayout>
                <Grid container justifyContent="center">
                    <Pages />
                </Grid>
            </PageLayout>
            </MsalProvider>
        );
    }
    
    const Pages = () => {
        return (
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/profile" element={<Profile />} />
            </Routes>
        );
    }
    
    export default App;
    

    SignInButton.jsx

    import Button from '@mui/material/Button';
    
    import { useMsal } from '@azure/msal-react';
    
    
    export const SignInButton = () => {
        const {instance} = useMsal();
    
        const handleSignIn = () => {
            instance.loginRedirect({
                scopes: ['user.read']
            });
        }
    
        return (
            <Button color="inherit" onClick={handleSignIn}>Sign in</Button>
        )
    };
    

    index.js

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    
    import { ThemeProvider } from '@mui/material/styles';
    import { theme } from "./styles/theme";
    
    import { BrowserRouter } from "react-router-dom";
    
    import App from './App';
    
    import { PublicClientApplication } from '@azure/msal-browser';
    
    const pca = new PublicClientApplication({
        auth: {
            clientId: '7006179e-2a1a-4790-9847-xxxxxxxxx',
            authority: 'https://login.microsoftonline.com/3f5c7a77-062d-426c-8582-xxxxxxxxxxx',
            redirectUri: '/',
        }
    });
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
        <React.StrictMode>
            <BrowserRouter>
                <ThemeProvider theme={theme}>
                    <App msalInstance={pca} />
                </ThemeProvider>
            </BrowserRouter>
        </React.StrictMode>
    );
    

    enter image description here

    When I ran http://localhost:3000 in browser, I got below screen:

    enter image description here

    After clicking Sign In button, I got login screen to pick account like below:

    enter image description here

    When I selected account in which application with provided client ID exists, I got consent screen like this:

    enter image description here

    After approving the consent, user signed in successfully with below screen:

    enter image description here

    In your case, check whether you are passing AppID of application in clientId parameter or not.

    To reproduce the error, I changed code by replacing AppID with ObjectID of application in clientId parameter

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    
    import { ThemeProvider } from '@mui/material/styles';
    import { theme } from "./styles/theme";
    
    import { BrowserRouter } from "react-router-dom";
    
    import App from './App';
    
    import { PublicClientApplication } from '@azure/msal-browser';
    
    const pca = new PublicClientApplication({
        auth: {
            clientId: 'bfd0d11b-0dd4-4acd-bbab-xxxxxxxxxx',
            authority: 'https://login.microsoftonline.com/3f5c7a77-062d-426c-8582-xxxxxxxxxxx',
            redirectUri: '/',
        }
    });
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
        <React.StrictMode>
            <BrowserRouter>
                <ThemeProvider theme={theme}>
                    <App msalInstance={pca} />
                </ThemeProvider>
            </BrowserRouter>
        </React.StrictMode>
    );
    

    enter image description here

    I got same error immediately after I clicking Sign In button like below:

    enter image description here

    To resolve the error, make sure to pass AppID of application that can be found here:

    enter image description here