MSAL和React-Admin集成

问题描述 投票:0回答:1

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

我使用了微软提供的代码,并将其放在App.js中的Constructor中,使用重定向方法可以正常工作,但我一直得到一个默认的React-Admin登录屏幕,在它重定向到MS认证页面之前的一瞬间。

如果我把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;
react-admin msal
1个回答
1
投票

我在你的例子上做了一点工作,我有一个解决方案.我主要阅读了React-Admin教程。https:/marmelab.comreact-adminTutorial.html。但同时也是一个自定义的React AAD MSAL库文档。https:/www.npmjs.compackagereact-aad-msal#react-aad-msal

请通过docs示例将这样的包添加到你的项目中。

我的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 登出按钮合并。https:/marmelab.comreact-admindoc2.8Authentication.html#customizing-the-login-and-logout-components。以及如何调用以下MSAL注销函数。https:/www.npmjs.compackagereact-aad-msal#azuread-component

© www.soinside.com 2019 - 2024. All rights reserved.