【问题标题】:MSAL and React-Admin integrationMSAL 和 React-Admin 集成
【发布时间】:2020-05-06 15:21:41
【问题描述】:

如何正确地将 MSAL 与 React-Admin 集成。

我使用了 Microsoft 提供的代码并将其放入 App.js 中的构造函数中,并且使用重定向方法可以正常工作,只是在重定向到 MS 身份验证之前,我会在瞬间获得默认的 React-Admin 登录屏幕页面。

如果我将 MSAL 代码放在我的自定义登录页面(空页面)中,它会进入循环并且身份验证不起作用。

如何摆脱 React-Admin 登录屏幕?

import { UserAgentApplication } from 'msal';

class App extends Component {

    constructor(props) {
      super(props);

      this.userAgentApplication = new UserAgentApplication({
        auth: {
          clientId: config.appId,
          authority: config.authEndPoint,
        },
        cache: {
          cacheLocation: "localStorage",
          storeAuthStateInCookie: true
        }
      });

      this.userAgentApplication.handleRedirectCallback(this.authCallback.bind(this));

      var user = this.userAgentApplication.getAccount();
      if (user != null) {
        localStorage.setItem('token', user.idToken);
        localStorage.setItem('userName', user.userName);
        const userName = user.userName.toString();

        fetch('http://localhost:5000/getuserid', {
          mode: 'cors',
          method: "GET",
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'USERNAME': userName
          },
        }).then(res => res.json())
          .then(res => {
            if (res.id != null) {
                localStorage.setItem('userID', res.id);
            } else {
              console.log('Failed to retreived id');
            }
          }).catch(
            err => console.log(err))
      }

      this.state = {
        isAuthenticated: (user !== null),
        user: {},
        error: null
      };

      if (user) {
        // Enhance user object with data from Graph
        //this.getUserProfile();
      }
      else {
        const loginRequest = {
          scopes: ["https://graph.microsoft.com/User.Read"]
        }

        this.userAgentApplication.loginRedirect(loginRequest);
      }
    }

    authCallback(error, response) {
      //handle redirect response
      this.setState({
        authenticated: true
      });
    }

  render() {
    return (
      <Admin title="MyApp" >
    ...
      </Admin>
    );
  }
}
export default App;

【问题讨论】:

  • 你能用代码示例更新你的帖子吗?
  • 我已更新帖子以包含我在 App.js 中使用的 MSAL 代码。该应用程序需要在 Azure AD 中注册,但为了工作,配置位于单独的 confg.js 字段中

标签: react-admin msal


【解决方案1】:

我在您的示例上做了一些工作,我有一个解决方案。 我主要阅读 React-Admin 教程https://marmelab.com/react-admin/Tutorial.html 还有一个自定义的 React AAD MSAL 库文档https://www.npmjs.com/package/react-aad-msal#react-aad-msal

请通过文档示例将此类包添加到您的项目中。

我的 App.js 代码:

import React from 'react';
import ReactDOM from 'react-dom';
import {Admin, ListGuesser, Resource} from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
import { AzureAD } from 'react-aad-msal';

// import App from './App';
import { authProvider } from './authProvider';

const dataProvider = jsonServerProvider('https://jsonplaceholder.typicode.com');

const AdminApp = () => (
  <Admin dataProvider={dataProvider}>
    <Resource name="users" list={ListGuesser}/>
  </Admin>
);

const App = () => (
  <AzureAD provider={authProvider} forceLogin={true}>
    <AdminApp />
  </AzureAD>
);

export default App;

对于 authProvider.js

// authProvider.js
import { MsalAuthProvider, LoginType } from 'react-aad-msal';

// Msal Configurations
const config = {
  auth: {
    authority: 'https://login.microsoftonline.com/MY_TENANT_ID/',
    clientId: 'MY_APP_ID',
    redirectUri: 'http://localhost:3000/'
  },
  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true
  }
};

// Authentication Parameters
const authenticationParameters = {
  scopes: [
    'User.Read'
  ]
}

// Options
const options = {
  loginType: LoginType.Redirect,
  tokenRefreshUri: window.location.origin + '/auth.html'
}

export const authProvider = new MsalAuthProvider(config, authenticationParameters, options)

该解决方案仅在 MS 身份验证成功时才显示 react-admin。 它根本没有使用默认的登录页面。

下一步可能是使用基于以下文档的 react-admin logout 按钮将该解决方案合并: https://marmelab.com/react-admin/doc/2.8/Authentication.html#customizing-the-login-and-logout-components 以及如何调用以下 MSAL 注销函数: https://www.npmjs.com/package/react-aad-msal#azuread-component

【讨论】:

    猜你喜欢
    • 2022-09-29
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多