将ActiveDirectory Javascript代码集成到React中

时间:2018-10-10 17:06:21

标签: javascript reactjs react-native active-directory react-router

我有这个Javascript代码来处理ActiveDirectory身份验证。 我需要创建一个使用此代码的React组件,在React中实现此目标的最佳方法是什么?

var config = { url: 'ldap://compandomain.com:389',
           baseDN: 'dc=domainname,dc=com',
           username: 'user',
           password: 'pass' };

var ad = new ActiveDirectory(config);
var username = 'john.smith@domain.com';
var password = 'password';

ad.authenticate(username, password, function(err, auth) {
  if (err) {
    console.log('ERROR: '+JSON.stringify(err));
    return;
  }

  if (auth) {
    console.log('Authenticated!');
  }
  else {
    console.log('Authentication failed!');
  }
});

React组件如下所示:

export default class ActiveDirectory extends React.Component {

  ..
  ......
  .........

  render() {
    return <div ..../>;
  }
}

1 个答案:

答案 0 :(得分:1)

您应该能够在componentDidMount生命周期方法中处理此身份验证。它应该看起来像这样。

import React from 'react';
import ActiveDirectory from 'activedirectory';

export default class ActiveDirectoryComponent extends React.Component {
  state = {
    authResponse: undefined
  };

  componentDidMount() {
    var config = {
      url: 'ldap://compandomain.com:389',
      baseDN: 'dc=domainname,dc=com',
      username: 'user',
      password: 'pass'
    };

    var ad = new ActiveDirectory(config);
    var username = 'john.smith@domain.com';
    var password = 'password';

    ad.authenticate(username, password, function (err, auth) {
      if (err) {
        this.setState({ authResponse: { error: JSON.stringify(err) } });
        return;
      }

      if (auth) {
        this.setState({ authResponse: auth });
      } else {
        console.log('Authentication failed!');
        this.setState({ authResponse: { authFailed: true } });
      }
    });
  }

  render() {
    if (!this.state.authResponse) {
      return <div>Authenticating....</div>;
    }
    if (this.state.authResponse.error) {
      return <div>{this.state.authResponse.error}</div>
    }
    if (this.state.authResponse.authFailed) {
      return <div>Authentication Failed</div>
    }
    return <div>.....</div>
  }
}