如何使用 passport-ldapauth 库在 Nestjs 应用程序中使用动态 ldap 配置选项?

How to use dynamic ldap config options in a Nestjs app using passport-ldapauth library?

我正在尝试在 Nestjs 应用程序中使用 passport-ldapauth 对活动目录进行身份验证。我没有服务帐户,想使用用户名作为 DN 绑定到 Active Directory。我正在尝试使用异步配置检索,但是在策略 class 的构造函数中调用 super() 时 运行 遇到了问题。

我收到以下错误:

src/ldap.strategy.ts:12:9 - 错误 TS17009:在派生 class 的构造函数中访问 'this' 之前必须调用 'super' . 12 超级 (this.getLdapConfig,

知道如何在调用 super() 时通过扩展策略 interface/passing 动态配置方法在 Nestjs 应用程序中完成这项工作吗?

我的代码:

import * as Strategy from 'passport-ldapauth';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { readFileSync } from 'fs';
import { callbackify } from 'util';

@Injectable()
export class LdapStrategy extends PassportStrategy(Strategy, 'ldap') {
    constructor(
    ) {     
        super(this.getLdapConfig,
         async (req: Request, user: any, done) => {
            console.log(req);
            req.user = user;
            return done(null, user);
        });
    }

    getLdapConfig(req: Request, callback: any) {
        
        process.nextTick(() => {
        let opts = {
            passReqToCallback: true,
            server: {
                url: 'ldaps://eassec.cc.corp:636',
                bindDN: `CN=${req.username}`,
                bindCredentials: '${req.password}',
                tlsOptions: {
                    ca: [
                        readFileSync('./src/public.crt')
                    ],
                    rejectUnauthorized: false
                },
                searchBase: 'ou=BU-IT',
                searchFilter: `(&(&(objectClass=person)(objectClass=user))(sAMAccountName=${req.username}))`
                searchAttributes: ['displayName', 'mail'],
            }

        };

            callback(null, opts);
        });
    }

}

您可以将 getLdapConfig 提取到在 class 之外声明的 const(箭头函数)或常规函数,然后将其传递到 super 调用中。

它本身不引用任何 class 成员,因此没有理由它必须是 class 方法。