简体   繁体   English

直接访问 URL(在我的例子中是本地主机)时,如何在不使用按钮的情况下弹出登录屏幕(Azure AD)?

[英]How to popup login screen(Azure AD) without using a button when accessing URL(local host in my case) directly?

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.我创建了一个基本的反应应用程序,我在其中实现了路由的概念,并且我使用了 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.当我尝试使用登录按钮登录时,它工作正常,但我希望当我尝试访问主页时,它会自动重定向到登录页面(Microsoft 登录),而无需单击任何按钮。

This is my code for "App.js" and in "AuthConfig" I have simply declared my clientId, redirecturi, scopes and authority.这是我的“App.js”代码,在“AuthConfig”中我只是声明了我的 clientId、redirecturi、范围和权限。


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;

If you simply want the login function to be called automatically when the App component mounts instead of when the button is clicked you can do this in the componentDidMount lifecycle method.如果您只是希望在App组件安装时自动调用login function 而不是在单击按钮时,您可以在componentDidMount生命周期方法中执行此操作。

Example:例子:

class App extends React.Component<any, any> {
  publicClientApplication: PublicClientApplication;

  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isAuthenticated: false,
      user: {}
    };

    this.publicClientApplication = new PublicClientApplication({
      auth: {
        clientId: config.appId,
        redirectUri: config.redirectUri,
        authority: config.authority
      },
      cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false
      }
    });
  }

  componentDidMount() {
    this.login();
  }

  login = sync () => {
    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 && (
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<Prices />} />
            </Routes>
          </BrowserRouter>
        )}
        <BrowserRouter>
          <Routes>
            <Route path="/Money" element={<Money />} />
            <Route path="/Ticket" element={<Ticket />} />
          </Routes>
        </BrowserRouter>
      </div>
    );
  }
}

I'm also not sure what is going on with usage of two routers, you'll very likely want to merge these so all routes are rendered within the same single routing context.我也不确定使用两个路由器会发生什么,您很可能希望合并它们,以便所有路由都在同一个路由上下文中呈现。

Example:例子:

<div className="App">
  <BrowserRouter>
    <Routes>
      <Route
        path="/"
        element={this.state.isAuthenticated ? <Prices /> : null}
      />
      <Route path="/Money" element={<Money />} />
      <Route path="/Ticket" element={<Ticket />} />
    </Routes>
  </BrowserRouter>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Msal Azure AD -> 重定向到 azure 登录屏幕 - Msal Azure AD -> redirect to azure login screen React.js msal 广告直接认证,无需任何登录按钮 - React.js msal ad authentication directly without any login button 如何通过输入URL来阻止用户直接访问我的反应应用页面,并将其重定向回登录页面 - How to I prevent user from accessing the page of my react app directly by entering the URL, and redirect them back to login page 如何使用@msal 在十分钟后触发会话过期弹出窗口 - react 和 azure ad - How to trigger an session expired popup after ten minutes using @msal - react and azure ad 防止 React Router 在不导航的情况下直接访问 URL - Prevent React Router from accessing directly an URL without navigating 访问受 Azure AD 保护的 API 时出现 401 - Getting 401 when accessing API protected with Azure AD 获取访问令牌和登录时出现Azure AD错误 - Azure AD error when fetching access token & login React - 如何在我的情况下调用弹出窗口? - React - how to invoke popup window in my case? 如何在 React APP 中启用 Azure AD B2C 登录 - How to Enable Azure AD B2C Login in React APP 直接访问 url 时,如何修复“无法读取未定义的属性‘文档’”? Next.js 和 apexcharts 库 - How can I fix "Cannot read property 'document' of undefined" when directly accessing the url? Next.js and apexcharts lib
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM