I have created a basic application of react in which I have implemented the concept of routing and for authentication I have used Azure AD. Its working fine when I try to login using the login button but I want that when I try to access the home page it automatically redirects to the login page(Microsoft login) without clicking any button.
This is my code for "App.js" and in "AuthConfig" I have simply declared my clientId, redirecturi, scopes and authority.
import Prices from "./pages/Prices";
import Ticket from "./pages/Ticket";
import Money from "./pages/Money";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import {config} from "./AuthConfig";
import {PublicClientApplication} from '@azure/msal-browser';
import React from "react";
class App extends React.Component<any, any>{
publicClientApplication: PublicClientApplication;
constructor(props){
super(props);
this.state = {
error: null,
isAuthenticated: false,
user:{}
};
this.login=this.login.bind(this)
this.publicClientApplication = new PublicClientApplication({
auth:{
clientId: config.appId,
redirectUri: config.redirectUri,
authority: config.authority
},
cache:{
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false
}
});
}
async login(){
try{
await this.publicClientApplication.loginPopup(
{
scopes: config.scopes,
prompt:"select_account"
});
this.setState({isAuthenticated:true})
}
catch(err){
this.setState({
isAuthenticated:false,
user:{},
error:err
});
}
}
logout(){
this.publicClientApplication.logoutPopup();
}
render() {
return(
<div className="App">
{this.state.isAuthenticated ? <p>
<BrowserRouter>
<Routes>
<Route path="/" element={<Prices />} />
</Routes>
</BrowserRouter>
</p>:
<p>
<button onClick={() => this.login()} > Login </button>
</p>
}
<BrowserRouter>
<Routes>
<Route path="/Money" element={<Money />}></Route>
<Route path="/Ticket" element={<Ticket/>}></Route>
</Routes>
</BrowserRouter>
</div>
);
}
}
export default App;