具有不同配置(SAML)的相同通行证js策略

时间:2019-12-09 13:03:33

标签: javascript node.js passport.js nestjs passport-saml

我正在尝试使用Okta作为身份提供者和Passport-saml库在Nest.js应用程序中创建SSO。我阅读了Nest身份验证和Passport-saml的文档。我对示例的理解没有问题,但是我确实需要使用具有不同配置的SAML策略,具体取决于POST api/auth/saml的请求正文值。换句话说,我有一个策略,但是我的自定义 LoginSSOStrategy类使用了不同的 entryPoint,颁发者,证书参数,该参数扩展了Nest的 PassportStrategy类 .js。有什么想法可以解决吗?

2 个答案:

答案 0 :(得分:1)

我不太确定这是否是一个好方法,但是如果您愿意,可以将类请求的范围设置为一定范围,然后通过构造函数将请求注入,然后可以访问请求对象并可以使用每个请求都有新的护照策略实例。您可以使用该请求将req.whatever传递给super()类的构造函数。

@Injectable({ scope: Scope.REQUEST })
export class LoginSSOStrategy exends PassportStrategy(Strategy) {

  constructor(@Inject(REQUEST) request: Request, ...) {
    super({/* options matching to request.field */});
  }

  validate(/* validate params*/) {
    /* validate functionality */
  }
}

您似乎需要做很多测试,以确保它可以与并发请求一起使用,但是总体上,至少从理论上讲,它可以工作。

答案 1 :(得分:0)

我认为此问题与此 GitHub issue 类似。由于 Passport.js 的全局特性以及 Nest 无法确定哪些路由使用 Passport 护照策略这一事实,因此无法使用 @Injectable({ scope: Scope.REQUEST }) 创建请求范围的 Passport 策略。

最近,我不得不使用基于传入请求中的一些数据的动态重定向 URL 来实现 Azure Active Directory 登录。根据您使用的策略,您可以在使用(未记录的)extraAuthReqQueryParams 属性调用 Passport 策略的 authenticate 方法时覆盖某些选项。 了解您是否能够覆盖某些选项的一种方法是查看文档,如果您感到幸运,可以查看您正在使用的 Passport 策略的源代码。在阅读了 undocumented feature 并在 source code of the Azure AD Passport strategy 中看到这些行(特别是 #1355 和 #1374 行)后,我能够通过使用更改我之前在 redirectUrl 属性中指定的值redirect_uri 属性(注意这里的细微差别)。

@Injectable()
export class AzureOIDCStrategy extends PassportStrategy(OIDCStrategy,'AzureOIDC') {
  constructor() {
    super({
      // Even though it is overwritten in the 'authenticate' method the Passport Strategy expects this to be set to a valid URL.
      redirectUrl: `https://your-backend-domain.com/auth/azure/callback`,
      // This ensures we have access to the request in the `authenticate` method
      passReqToCallback: true,
    });
  }

  authenticate(req: Request, options: Record<string, any>): void {
    return super.authenticate(req, {
      // `options` may contain more options for the `authenticate` method in Passport.
      ...options,
      extraAuthReqQueryParams: {
        // This overwrites the `redirectUrl` specified in the constructor
        redirect_uri: `https://${req.headers.host}/auth/callback`,
      },
    });
  }
}

我希望您能够应用此“策略”来更新 entryPointissuercert 参数。

在 Express 应用中,您可以执行以下操作:

app.get('/login', 
  (req, res, next) =>
    passport.authenticate('azure-ad', {
      extraAuthReqQueryParams: {
        redirect_uri: `https://${req.headers.host}/auth/callback`,
      },
  })(req, res, next)
);