Microsoft's AD login first appeared in 1999, which is what we know as SSO, and the specific principles will not be expanded too much. see official website
install dependencies
"@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
The front-end implements the logic. Anyone who has done WeChat applets knows that the development of applets requires a developer id, or an enterprise id. Similarly, AD login also has a similar clientId. Create a new folder Auth in src, and create authConfig.ts and useB2CPopupLoginService.ts under Auth
specific code
1. Login page
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 callback address
3、useB2CPopupLoginService.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 };
}
That's it. . . Now the annoying thing about azure is that it needs SMS verification or mobile app consent to complete the final login
There are two more ways to log in. The common username login is fine, so I won’t introduce it.
National Secret Standard Ukey Web Login Authentication Process