代码之家  ›  专栏  ›  技术社区  ›  mbenhalima

将ActiveDirectory Javascript代码集成到React中

  •  0
  • mbenhalima  · 技术社区  · 6 年前

    我需要创建一个使用此代码的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 回复  |  直到 6 年前
        1
  •  2
  •   Joey    6 年前

    您应该能够在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>
      }
    }