umi3.5微软的AD登录loginRedirect

这篇具有很好参考价值的文章主要介绍了umi3.5微软的AD登录loginRedirect。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

umi3.5微软的AD登录loginRedirect

 我这边技术栈是react+ts 如果你是vue,直接将tsx文件改成jsx就可以或者不该也没问题

 上篇文章介绍了msal 的弹框登录,先介绍下重定向登录这个相对弹框登录要烦很多。。。中国内网看我查询的资料很少,只有微软系的公司才会有相对应的需求。此处自己研究了2天并实现了功能现分享给大家。

思路我们实现重定向登录。顾名思义就是我先在msal服务登录成功,并成功通过msal api拿到登陆后信息accounts,isAuthenticated。根据accounts获取令牌(token),再将令牌与我们自己后端api去认证改用户是否可以登录此系统(欧莱雅一个公司几万人不是所有的人都可以登录所以加了这个接口认证)。重定向登录一定要组件化并要包裹layout 否者无法实现,这点给弹框登录的最大区别。

点击按钮代码以及调用登录方法handleLogin('redirect');就不做解释了,这个很简单

1、环境配置文件相关参数全局新建 authConfig.js

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */

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

/**
 * Configuration object to be passed to MSAL instance on creation.
 * For a full list of MSAL.js configuration parameters, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
 */
export const msalConfig = {
  auth: {
    clientId: '277e3d78-7012-4c89-8e32-', // 公司在msal客户端编号 ,给微信小程序的id 一样
    authority:
      'https://login.microsoftonline.com/e4e1abd9-eac7-4a71-ab52-', //由应用程序的身份提供者实例和登录受众组成,可能还有租户 ID
    redirectUri: process.env.REDIRECT_URL, // 重定向的地址就是自己前端发布的访问地址,比如dev环境 http://localhost:8002
    tenantId: 'e4e1abd9-eac7-4a71-ab52-',
    scope: 'api://277e3d78-7012-4c89-8e32-/default',
    postLogoutRedirectUri: 'https://pto-test.lindemobile.cn/#/logout',
    navigateToLoginRequestUrl: false,
  },
  cache: {
    cacheLocation: 'localStorage', // This configures where your cache will be stored
    storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        if (containsPii) {
          return;
        }
        switch (level) {
          case LogLevel.Error:
            console.error(message);
            return;
          case LogLevel.Info:
            console.info(message);
            return;
          case LogLevel.Verbose:
            console.debug(message);
            return;
          case LogLevel.Warning:
            console.warn(message);
            return;
          default:
            return;
        }
      },
    },
  },
};

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
export const loginRequest = {
  scopes: [msalConfig?.auth.scope],
};

/**
 * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
export const graphConfig = {
  graphMeEndpoint: 'Enter_the_Graph_Endpoint_Herev1.0/me', //e.g. https://graph.microsoft.com/v1.0/me
};
export const tokenRequest = {
  scopes: [msalConfig?.auth.scope],
  forceRefresh: false, // Set this to "true" to skip a cached token and go to the server to get a new token
};

2、layouts文件

import { theme } from '@/app/config/theme';
import useAuthService, { AuthService } from '@/modules/User/useAuthService';
import useFilesService from '@/modules/File/useFileService';
import useFormatLanguageService, {
  FormatLanguageService,
} from '@/tools/formatLanguage';
import { UseRequestProvider } from 'ahooks';
import 'antd/dist/antd.less';
import axios from 'axios';
import React, { useState } from 'react';
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { IRouteComponentProps } from 'umi';
import './layouts.less';
import bg from '@/assets/images/bg.jpg';
import heardBG from '@/assets/images/heardBG.png';
import background from '../../public/images/background.jpg';
import { getToken } from '@/uitls/auth';
import GetAuth from './AADLogin';

export default function Layout({
  children,
  location,
  route,
  history,
  match,
}: IRouteComponentProps) {
  const [loginSuccess, setLoginSuccess] = useState(false);
  const formatLanguageService = useFormatLanguageService();
  const fileService = useFilesService();
  let token = getToken();
  const authService = useAuthService({
    mode: token ? '' : 'normal',
    formatLanguageService,
    defaultRoute: '/login',
    token,
  });
  return (
    // 注入主题样
    <ThemeProvider theme={theme}>
      <GetAuth //必须作为父盒子
        onLoginSuccess={() => setLoginSuccess(true)}
        loginSuccess={loginSuccess}
      >
        <UseRequestProvider
          value={{
            requestMethod: (param) =>
              axios(param).then((r) => {
                return r.data;
              }),
          }}
        >
          {children}
        </UseRequestProvider>
      </GetAuth>
    </ThemeProvider>
  );
}

3、给layout 文件同级新建AADLogin.tsx

import React, { useState } from 'react';
import { useEffect } from 'react';

import {
  InteractionStatus,
  PublicClientApplication,
} from '@azure/msal-browser';
import { useIsAuthenticated, useMsal, MsalProvider } from '@azure/msal-react';

import { message } from 'antd';
import { history } from 'umi';
import { loginRequest, msalConfig } from '@/authConfig';
import Loading from '@/components/Loading';
import { GetUserInfo, ThirdLogin } from '@/app/request/requestApi';
import { setMenus, setRefershToken, setToken } from '@/uitls/auth';

export interface LoginProps {
  onLoginSuccess?: () => void;
  loginSuccess?: boolean;
  children?: any;
}
// 一定要放在最外层
//下面的所有组件MsalProvider都可以通过上下文访问PublicClientApplication实例,以及@azure/msal-react.
const msalInstance = new PublicClientApplication(msalConfig);

function GetAuthSub(props: LoginProps) {
  console.log(props, '--------');
  const [loading, setLoading] = useState<boolean>(false);
  const { instance: msalObject, accounts, inProgress } = useMsal();
  const isAuthenticated = useIsAuthenticated(); //判断用户是否通过身份验证
  useEffect(() => {
    msalInstance
      .handleRedirectPromise()
      .then((s) => {
        console.log(s);
        if (s !== null && s.account != null)
          //        currentAccount.setCurrentAccount(s.account.username, s.account.homeAccountId, s.account.tenantId);
          console.log('success');
      })
      .catch((a: any) => {
        console.log('err');
        console.log(a);
      });
  }, []);
  useEffect(() => {
    if (sessionStorage.getItem('loginType') !== 'Gool') {
      props.onLoginSuccess();
      console.log(accounts, inProgress, isAuthenticated, '--------');
      if (inProgress === InteractionStatus.Logout) {
        return;
      }
      //登录 如果要初始化就调用Az登录放开此处
      if (inProgress === InteractionStatus.None && !isAuthenticated) {
        // msalInstance.loginRedirect(loginRequest);
      }
      if (
        inProgress === InteractionStatus.None &&
        accounts.length > 0 &&
        isAuthenticated &&
        !sessionStorage.getItem('ADToken')
      ) {
        const curAccount = msalInstance.getActiveAccount() || accounts[0];
        const tokenRequest = {
          account: curAccount,
          scopes: [...loginRequest.scopes],
        };
        //获取访问令牌 token
        msalInstance.acquireTokenSilent(tokenRequest).then((response) => {
          sessionStorage.setItem('ADToken', response?.accessToken);
          // 调用自己后端认证msal token
          onThirdLogin(response?.accessToken);
        });
      }
    }
    //accounts登录信息  isAuthenticated是否授权
  }, [accounts, isAuthenticated, inProgress]);

  return <>{props.children}</>;
}
// 获取token
const onThirdLogin = (accessToken) => {
  Loading.show();
  const params = {
    accessToken,
    type: 7,
    code: 'code',
    clientType: 0,
  };
  ThirdLogin(params)
    .then((res) => {
      if (res.success) {
        message.success('Login succeeded');
        sessionStorage.setItem('loginType', 'AD');
        setToken(res.data.accessToken);
        setRefershToken(res.data.refreshToken);
        Loading.hide();
        onGetUserInfo('/LOREAL/allItems/items');
      } else {
        Loading.hide();
        message.error(res.msg);
        history.replace('/');
      }
    })
    .catch((err) => {
      Loading.hide();
      message.error(err.msg);
    });
};
// 用户信息
const onGetUserInfo = (homeRoute) => {
  GetUserInfo({}).then((res) => {
    if (res.success) {
      setMenus(JSON.stringify(res.data.menus));
      sessionStorage.setItem('realName', res.data.account.realName);
      sessionStorage.setItem('roles', res.data.account.roles[0]);
      history.replace(homeRoute);
    } else {
      message.error(res?.msg);
    }
  });
};
// 登录
export const handleLogin = (loginType) => {
  if (loginType === 'popup') {
    //弹框登录
    msalInstance.loginPopup(loginRequest).catch((e) => {
      console.log(e);
    });
  } else if (loginType === 'redirect') {
    //重定向登录
    msalInstance.loginRedirect(loginRequest);
  }
};
// 登出
export const signOut = () => {
  const logoutRequest = {
    postLogoutRedirectUri: msalConfig.auth.redirectUri,
    mainWindowRedirectUri: msalConfig.auth.redirectUri,
  };
  msalInstance.logoutRedirect(logoutRequest);
};
// 组件化 MsalProvider 获取msal授权流
const GetAuth = (props: LoginProps) => {
  return (
    <MsalProvider instance={msalInstance}>
      <GetAuthSub
        onLoginSuccess={props.onLoginSuccess}
        loginSuccess={props.loginSuccess}
      >
        {props.loginSuccess ? props.children : null}
      </GetAuthSub>
    </MsalProvider>
  );
};
export default GetAuth;

umi3.5微软的AD登录loginRedirect

umi3.5微软的AD登录loginRedirect

 umi3.5微软的AD登录loginRedirect

 umi3.5微软的AD登录loginRedirect

登录成功。。。

国内资料很少。如有疑问请留言。推荐用梯子去查资料

微软的AD登录loginPopup文章来源地址https://www.toymoban.com/news/detail-452436.html

到了这里,关于umi3.5微软的AD登录loginRedirect的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用python ldap3对接微软AD

    网上很多文档都是割裂的,此次使用python操作微软ad踩了不少坑,借助ChatGPT也没有用,记录一下正确信息。 环境信息: Windows Server 2019 Active Directory Domain Services DNS Server 以上环境需要提前安装完成,具体信息可以参考对应服务部署教程 为了避免重复造轮子,这一部分内容可以

    2024年02月06日
    浏览(27)
  • 【Azure】微软 Azure 基础解析(九)Azure 标识、身份管理、Azure AD 的功能与用途

    本系列博文还在更新中,收录在专栏:「Azure探秘:构建云计算世界」 专栏中。 本系列文章列表如下: 【Azure】微软 Azure 基础解析(三)云计算运营中的 CapEx 与 OpEx,如何区分 CapEx 与 OpEx 【Azure】微软 Azure 基础解析(四)Azure核心结构组件之数据中心、区域与区域对、可用

    2024年02月09日
    浏览(46)
  • 如何配置azure AD 通过登录azure的账户密码登录Azure VM

    Azure vm 添加 Azure AD 通过邮箱的账户密码登录 首先创建一个虚拟机,并且勾选Azure AD的复选框。 将创建虚机生成的资源最好配置到同一资源组 例如: 在vm生成的全部资源所在的资源组下打开访问控制

    2024年02月09日
    浏览(40)
  • 宁盾统一身份中台助力某集团公司实现统一身份认证和管理(如泛微OA、微软AD)

    某集团公司是一家以钢铁为主业,涉足互联网金融、文化健康、智慧城市、现代物流等多领域的大型现代化企业集团。创业发展已有三十余年,拥有员工人数超万人,为了提升管理效率,同时实现国产化创新和数字化转型,公司采用了泛微OA和微软AD作为两套账号管理系统。泛

    2024年02月04日
    浏览(35)
  • Java接入Microsoft Azure AD实现SSO登录

    应用程序通过单点登录解决账号创建问题 SSO(SingleSign-On,单点登录)通过在IDP(身份验证提供商)登录成功后,就可以访问IDP关联的应用程序以及相关权限 为了解决以下问题: 用户使用多个应用程序时,需要创建多个账号 如果用户在所有平台创建的账号密码一致,可能会

    2024年02月05日
    浏览(29)
  • windows10/11系统实现本地账户密码登录微软账户 微软账户取消pin登录

    Windows 10支持两种账户登录模式,一种是使用了多年的通过本地用户账户来登录系统,另一种则是使用Microsoft账户来登录系统。使用Microsoft账户登录Windows系统是从Windows 8开始支持的登录模式,这种登录模式会自动连接到微软,然后对账户信息与系统设置进行自动同步。 简单来

    2024年02月13日
    浏览(39)
  • win11微软账户登录一直转圈怎么解决?win11微软账户登录一直转圈

    win11微软账户登录一直转圈怎么解决?最近有很多小伙伴们向小编反映说自己的微软账户登录的时候一直在转圈就是进不去,不知道是怎么一回事,就卡在登录界面上。那遇到这个问题应该怎么解决呢?还不清楚的小伙伴们不用担心,跟着小编一起来看看解决方法吧! 这里有

    2024年02月07日
    浏览(45)
  • 基于群组实现从 Azure AD 到极狐GitLab 的单点登录

    目录 配置单点登录 在 Azure AD 中创建企业应用 SAML 基础配置 配置 Azure “Attributes Claims” 配置用户同步 在极狐GitLab 创建 SCIM Token 配置 Azure Provisioning Azure 手动用户预配 测试单点登录 Azure 自动用户同步 配置群组同步 配置 SAML 群组链接 Azure 配置 Group Claim 可能遇到的问题 单点登

    2024年02月11日
    浏览(34)
  • 微软 Authenticator更换登录设备

    微软 Authenticator更换登录设备 要把微软 Authenticator换到其它手机,网上查到需要备份-恢复等,但是操作时发现需要Google play服务,但是安装后仍提示未安装,后发现用如下方式可进行更换。 1、登录该网址 https://mysignins.microsoft.com/security-info 2、点击验证器应用后的—删除 3、点

    2024年02月05日
    浏览(31)
  • 微软、Google、Twitter、Facebook登录

    用户名密码方式的登录与注册繁琐,耗时长,用户体验差。 (1)官方文档地址 https://learn.microsoft.com/zh-cn/graph/auth/ (2)时序图 a、步骤10 服务器通过app获取到的授权码,请求Microsoft Graph获取令牌 POST /{tenant}/oauth2/v2.0/token Host: https://login.microsoftonline.com Content-Type: application/x-www-

    2024年02月04日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包