首页 > 解决方案 > 如何在 react-adal 中使用 withAdalLoginApi HOC 以避免登录 index.js?

问题描述

我正在使用react-adal在我的 react 应用程序中实现 azure 活动目录身份验证。我已经在我的前端应用程序中配置了 azure 广告,并且该应用程序通过 Microsoft 登录进行身份验证,并按预期重定向到我的仪表板。

我面临的问题是我不希望微软登录在第一次启动时弹出。目前发生的情况是在第一次启动应用程序时弹出微软登录,并且用户被迫进行身份验证。我希望用户首先转到自定义登录页面,当用户单击页面中的登录按钮时,应该会弹出 microsoft 登录并对用户进行身份验证并将他重定向到应用程序的仪表板。

adalConfig.js

import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';
import { SbaHelper } from '../helpers/SbaHelper';

export const adalConfig = {
  tenant: '<tenant-Id>',
  clientId: '<client-Id>',
  redirectUri: 'http://localhost:3000/dashboard',
  endpoints: {
    api: '', // <-- The Azure AD-protected API
  },
  oauth2AllowIdTokenImplicitFlow: true,
  cacheLocation: 'localStorage',
};
export const authContext = new AuthenticationContext(adalConfig);

// returns token from local storage.
export const getToken = () => authContext.getCachedToken(adalConfig.clientId);

export const adalApiFetch = (fetch, url, options) =>
  adalFetch(authContext, adalConfig.endpoints.api, fetch, url, options);

export const withAdalLoginApi = withAdalLogin(
  authContext,
  adalConfig.endpoints.api
);

index.js

如果我没记错的话,首先出现 microsoft login 的原因一定是因为我的整个应用程序都被 react adal 方法 runWithAdal()

import { runWithAdal } from 'react-adal';
import { authContext } from './config/adalConfig';

const DO_NOT_LISTEN = false;
/**
 *
 * wraps indexApp.js with the runWithAdal
 * method from react-adal, which ensures
 * the user is signed with Azure AD before
 * loading indexApp.js:
 *
 */
runWithAdal(
  authContext,
  () => {
    /**
     * This index wrap is needed because ADAL
     * use iframes for token silent refresh,
     * and we do not want to have duplicated
     * ReactApp started on iframes too!
     */
    // eslint-disable-next-line global-require
    require('./indexApp');
  },
  DO_NOT_LISTEN
);

indexApp.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
import * as serviceWorker from './serviceWorker';

import './index.css';
import './assets/styles/style.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

我不需要 ms 登录来显示并在首次启动时验证用户。我需要在第一次启动时显示我的登录页面,并且会有一个“登录”按钮,当用户单击该按钮时,会弹出 microsoft 登录,并且在用户通过输入他/她的 ms 登录凭据进行身份验证后,用户需要重定向到我的仪表板。

希望有人能帮我解决这个问题。谢谢

标签: reactjsazureauthenticationazure-active-directoryazure-authentication

解决方案


场景是用户进入自定义页面,然后需要重定向到AAD登录页面。自定义页面需要自己编写,认证环境需要自己在这个页面中设置,而不是在索引页面中。因为,AAD不知道你使用哪个页面作为认证。每件事都由开发这些页面的开发人员控制。


推荐阅读