umi4 实现msal aad 登录loginRedirect方式并获取令牌

2023-10-08 19:50

本文主要是介绍umi4 实现msal aad 登录loginRedirect方式并获取令牌,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在 Umi 4 中使用 Ant Design Pro Layout 以及 MSAL (Microsoft Authentication Library) 实现登录并获取令牌进入到首页,你需要按照以下步骤进行操作:

  1. 安装所需依赖:
    使用 npm 或 yarn 安装所需的包:

    npm install @azure/msal-browser @azure/msal-react ant-design/pro-layout

    yarn add @azure/msal-browser @azure/msal-react ant-design/pro-layout

2. 配置 MSAL:
在项目中创建一个新文件,例如 src/msalConfig.js。在此文件中,配置 MSAL 实例并导出它:

import { PublicClientApplication } from "@azure/msal-browser";  const msalConfig = {  auth: {  clientId: "your-client-id",  authority: "https://login.microsoftonline.com/your-tenant-id",  redirectUri: "http://localhost:8000",  },  
};  const msalInstance = new PublicClientApplication(msalConfig);  export { msalInstance };  

请将 your-client-id 和 your-tenant-id 替换为在 Azure Portal 中注册的应用程序的相应值。

注意:要想实现整个应用程序中管理用户的身份验证状态,在umi4之前layout 有children 属性直接用MsalProvider标签包裹就可以。而umi4没有使用Outlet标签替代children,思考如何实现呢

3、更新 src/app.tsx 以包含 MsalProvider

import React from 'react';  
import { history } from 'umi';  
import { msalInstance } from './msalConfig';  
import { MsalProvider } from '@azure/msal-react';  export function render(oldRender) {  oldRender();  
}  export function rootContainer(container) {  return React.createElement(  MsalProvider,  {  instance: msalInstance,  },  container  );  
}  

解释app.tsx

这段代码是一个umi插件的入口文件,其中包含了两个函数:renderrootContainer

render函数是umi框架提供的函数,在应用程序启动之前会被调用,用来执行一些额外的初始化操作。在这个示例中,oldRender参数是一个回调函数,它会在render函数执行完毕后被调用,以便继续渲染应用程序。

rootContainer函数则是应用程序的根组件,它接收一个名为container的参数,该参数表示应用程序中所有其他组件的层次结构。在这个示例中,rootContainer函数返回一个MsalProvider组件,它是Azure Active Directory中的一个React组件,用于在整个应用程序中管理用户的身份验证状态。

MsalProvider组件接收一个名为instance的属性,它是一个MSAL实例,用于管理身份验证和令牌获取等操作。在这个示例中,msalInstance是从@/layouts/msalConfig导入的,它是一个MSAL实例的配置文件,包含了应用程序的客户端ID和租户ID等信息。

最后,rootContainer函数使用React.createElement函数将MsalProvider组件和container参数一起传递,以便将其作为根组件渲染到应用程序中。

4. 创建一个登录组件,例如 src/pages/login/index.js,并实现 MSAL loginRedirect 方法:

import React from "react";  
import { useMsal } from "@azure/msal-react";  const Login = () => {  const { instance } = useMsal();  const handleLogin = () => {  const loginRequest = {  scopes: ["openid", "profile", "User.Read"],  // 换成自己的租户授权信息};  instance.loginRedirect(loginRequest);  };  return (  <div>  <button onClick={handleLogin}>Login with Microsoft</button>  </div>  );  
};  export default Login;  

5. 使用 Ant Design Pro Layout 和 Outlet 路由标签实现登录跳转:
在 src/layouts/index.js 中,使用 ProLayout 和 Outlet 标签并在成功登录并获取到令牌后执行跳转到首页:

import React, { useEffect } from "react";  
import ProLayout from "@ant-design/pro-layout";  
import { Outlet } from "react-router-dom";  
import { useMsal } from "@azure/msal-react";  
import { useHistory } from "react-router-dom";  const Layout = () => {  const { instance } = useMsal();  const history = useHistory();  useEffect(() => {  const handleRedirect = async () => {  const response = await instance.handleRedirectPromise();  if (response) {  // 登录成功,跳转到首页  history.push("/");  }  };  handleRedirect();  }, [instance, history]);  return (  <ProLayout>  <Outlet />  </ProLayout>  );  
};  export default Layout;  

使用此代码,当用户成功登录

注意,我们做的是单页面应用在 Azure 的时候按照以下步骤

 

 将redirectUri 设置为你的代码里的回调地址

拓展、

. 在成功登录后,你可以使用 msal-browser 的 instance 对象获取访问令牌并使用 Microsoft Graph API 获取用户信息。将以下代码添加到 src/layouts/index.js 文件中的 useEffect 函数内部:

useEffect(() => {  const handleRedirect = async () => {  const response = await instance.handleRedirectPromise();  if (response) {  // 登录成功,跳转到首页  history.push("/");  // 获取访问令牌  const accessTokenRequest = {  scopes: ["User.Read"],  account: instance.getAccountByUsername(response.account.username),  };  const accessTokenResponse = await instance.acquireTokenSilent(accessTokenRequest);  const accessToken = accessTokenResponse.accessToken;  // 使用访问令牌获取用户信息  const userResponse = await fetch("https://graph.microsoft.com/v1.0/me", {  headers: {  Authorization: `Bearer ${accessToken}`,  },  });  const userInfo = await userResponse.json();  console.log(userInfo);  }  };  handleRedirect();  
}, [instance, history]);  

这段代码首先使用 acquireTokenSilent 方法获取访问令牌,然后使用 fetch API 调用 Microsoft Graph API 的 /me 端点以获取用户信息。获取到的用户信息将被输出到控制台。

现在,当用户成功登录并获取令牌后,应用程序将获取用户信息并将其输出到控制台。你可以根据需要自定义此代码以将用户信息存储在状态管理库(如 Redux 或 MobX)中或直接在组件状态中。

案例开源代码umi4+react18+add

这篇关于umi4 实现msal aad 登录loginRedirect方式并获取令牌的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/167645

相关文章

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QGroupBox控件的实现

《Qt中QGroupBox控件的实现》QGroupBox是Qt框架中一个非常有用的控件,它主要用于组织和管理一组相关的控件,本文主要介绍了Qt中QGroupBox控件的实现,具有一定的参考价值,感兴趣... 目录引言一、基本属性二、常用方法2.1 构造函数 2.2 设置标题2.3 设置复选框模式2.4 是否

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法

《springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法》:本文主要介绍springboot整合阿里云百炼DeepSeek实现sse流式打印,本文给大家介绍的非常详细,对大... 目录1.开通阿里云百炼,获取到key2.新建SpringBoot项目3.工具类4.启动类5.测试类6.测

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo