Microsoft AD ログインログインポップアップ

Microsoft の AD ログインは 1999 年に初めて登場しました。これは私たちが SSO として知っているものであり、特定の原則はあまり拡張されません。公式ウェブサイトを見る

AD公式サイト

依存関係をインストールする

    "@azure/msal-browser": "^2.15.0",
    "@azure/msal-react": "^1.0.1",

    //npm install react react-dom
    npm install @azure/msal-react @azure/msal-browser

フロントエンドはロジックを実装します。WeChat アプレットを使用したことがある人なら誰でも、アプレットの開発には開発者 ID またはエンタープライズ ID が必要であることを知っています。同様に、AD ログインにも同様の clientId があります。src に新しいフォルダー Auth を作成し、Auth の下に authConfig.ts と useB2CPopupLoginService.ts を作成します。

特定のコード

1. ログインページ

import useB2CPopupLoginService from '@/modules/User/Auth/useB2CPopupLoginService';
export default function LoginForm(){
const { signIn } = useB2CPopupLoginService(); // ad登录
  const loginAD = () => {
    signIn();
  };
return (
    <>
          <Button
            onClick={loginAD}
            block
          >
            AD登录
          </Button>
    </>
}

2、authConfig.ts

/**
 * 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
 */
import { LogLevel } from '@azure/msal-browser';
 export const msalConfig = {
    auth: {
        clientId: "277e3d78-7012-4c89-8e32",
        authority: "https://login.microsoftonline.com/e4e1abd9-eac7-4a71-ab52",
        redirectUri: process.env.REDIRECT_URL, // 回调地址
        tenantId: "e4e1abd9-eac7-4a71-ab52",
        scope: "api://277e3d78-7012-4c89-8e32/default",
        postLogoutRedirectUri:"https://pto-test.lindemobile.cn/#/logout"
    },
    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
    },
    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;
                }
            }
        }
    }
};

/**
 * 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 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
};

 process.env.REDIRECT_URL コールバック アドレス

 3、B2CPopupLoginService.tsを使用する

import { PublicClientApplication } from '@azure/msal-browser';
import { loginRequest, msalConfig } from './authConfig';
import { useContext, useState } from 'react';
import message from 'antd/lib/message';
import { history } from 'umi';
import { GetUserInfo, ThirdLogin } from '@/app/request/requestApi'; // 获取token 与GetUserInfo用户信息接口
import Loading from '@/components/Loading';
import { setMenus, setRefershToken, setToken } from '@/uitls/auth';
const myMSALObj = new PublicClientApplication(msalConfig);

export default function useB2CPopupLoginService() {

  const onSignInSuccess = (response) => {
    if (!response || !response?.accessToken) {
      message.warning(response.msg);
      return;
    }
    message.success('Login succeeded');
    // 调用后端token 此处根据自己实际开发情况替换后端接口
    const params = {
      accessToken: response?.accessToken,
      type: 7,
      code: 'code',
      clientType: 0,
    };
    ThirdLogin(params).then((res) => {
      Loading.show();
      if (res.success) {
        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);
      }
    });
  };
  // 用户信息
  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)
      }
    });
  };
//登录
  const signIn = () => {
    myMSALObj
      .loginPopup(loginRequest)
      .then(onSignInSuccess)
      .catch((error) => {
        message.warning(`${error}`);
      });
  };
// 退出
  function signOut() {
    const logoutRequest = {
      postLogoutRedirectUri: msalConfig.auth.redirectUri,
      mainWindowRedirectUri: msalConfig.auth.redirectUri,
    };
    myMSALObj.logoutPopup(logoutRequest);
  }

  return { signIn, signOut };
}

それでおしまい。Azure の厄介な点は、最終ログインを完了するには SMS 認証またはモバイル アプリの同意が必要なことです。

ログイン方法はあと2つありますが、共通ユーザー名でのログインで良いので紹介しません。

Google認証ログイン

国家機密標準 Ukey Web ログイン認証プロセス

 Microsoft 認証ライブラリ-JS

 Microsoft AD ログインログインリダイレクト

おすすめ

転載: blog.csdn.net/weixin_46600931/article/details/128564547