Microsoft sso login is not logging in the user neither getting details about the account

53 views Asked by At

This is my react app which handles sso login using a subdomain and fetches configuration dynamically. This is my code for a hook which fetches configuration dynamically from database.

import { useState, useEffect } from 'react';
import axios from 'axios'; 
interface AuthData {
    clientId: string;
    authority: string;
    redirectUri: string;
}


const useGetMFA = (subdomain:any) => {
    const [data, setData] = useState<AuthData | null>(null); // Initialize state to null
    const [error, setError] = useState(null); // State for handling errors
    
    useEffect(() => {
        const loadAsync = async () => {
            try {
                const response = await axios.get(`${process.env.REACT_APP_API_URL}outlook/organization/${subdomain}`);
                if (response.status === 200) {
                    const result = response.data?.data; // Using optional chaining
                    if (result) {
                       const auth: AuthData = 
                             {
                                clientId: result.outlook_client_id_mfo,
                                authority: `https://login.microsoftonline.com/${result.outlook_tenant_id_mfo}`,
                                redirectUri: 'http://localhost:3000/auth/redirectmsft', // Using an environment variable
                            };
                        setData(auth);
                    }
                }
            } catch (error) {
                setError(error); // Set the error state
            }
        };

        loadAsync();
    }, [subdomain]); // Include subdomain in the dependency array

    return { data, error }; // Return both data and error
};

export default useGetMFA;

This is code of MsalProvider:

import useGetMFA from './app/customhooks/getMFA';
import {PublicClientApplication,Configuration} from '@azure/msal-browser';
import {createContext, useContext} from 'react';

import { MsalProvider } from "@azure/msal-react";
const MyProvider = (props:any) =>{

    //get windows url data 
    const currentUrl = window.location.href;
    

    const urlObject = new URL(currentUrl);
    const hostname = urlObject.hostname;
    const subdomainParts = hostname.split('.');
    console.log(subdomainParts);
    let subdomain = subdomainParts.length > 1 ? subdomainParts[0] : '';
    console.log(`subdomain is `);
   
    
    if(subdomain=='www' || subdomain ==''){
      
        
    }

    console.log(subdomain);
    const data = useGetMFA(subdomain);
     
    console.log(data.data);
    
  
    const configuration: Configuration = {
        auth: data?.data,
        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>;
}

export default MyProvider;

The problem is that when I get redirected to my url of redirection I am seeing this issue

export function RedirectMSFT() {
  const { instance, accounts, inProgress } = useMsal();
  const { saveAuth, setCurrentUser } = useAuth();
 

  useEffect(() => {
    console.log('Effect triggered');
    console.log('In progress:', inProgress);
    console.log('Accounts:', accounts);
    console.log('Instance', instance);
    if (inProgress =="none") {
      console.log(`Inside in progress is equal to none`);
      if (accounts.length > 0) {
        // User is logged in
        console.log('User is logged in:', accounts);
  
        // Check for valid tokens
        const validTokensExist = accounts.some((account:any) => account?.idToken && account?.accessToken);
        
        if (validTokensExist) {
          // Fetch additional data if needed
          console.log('Fetching additional data...');
        } else {
          // Handle token acquisition failure
          console.error('Tokens are missing or expired.');
        }
      } else {
        // User is not logged in
        console.log('User is not logged in');
      }
    }
  
    // Add more debugging information or actions as needed
  
  }, [inProgress, accounts]);
  return (
    <>
        <div className="App">
            <h1>Redirecting...</h1>
         </div>
    </>
  );
}

I am unable to login because in console log, I am getting accounts as empty array even though sometimes I am able to get access but sometimes I don't. Need help regarding this where I am making mistake.

All I am seeing in my console log is a empty array of accounts and User is not logged in

0

There are 0 answers