我认为这个问题类似于GitHub issue。由于 Passport.js 的全球性以及 Nest 无法确定哪些路由使用 Passport 护照策略这一事实,因此无法使用 @Injectable({ scope: Scope.REQUEST }) 创建请求范围的 Passport 策略。
最近,我不得不根据传入请求中的一些数据使用动态重定向 URL 实现 Azure Active Directory 登录。根据您使用的策略,您可以在调用 Passport 策略的 authenticate 方法时使用(未记录的)extraAuthReqQueryParams 属性覆盖某些选项。
了解您是否能够覆盖某些选项的一种方法是检查文档,如果您感到幸运,您可以查看您正在使用的 Passport 策略的源代码。在阅读了undocumented feature 并在source code of the Azure AD Passport strategy 中看到这些行(特别是#1355 和#1374 行)后,我能够使用redirect_uri 属性更改我之前在redirectUrl 属性中指定的值(注意这里的细微差别)。
@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`,
},
});
}
}
我希望您能够应用此“策略”来更新entryPoint、issuer 和cert 参数。
在 Express 应用中,您可以执行以下操作:
app.get('/login',
(req, res, next) =>
passport.authenticate('azure-ad', {
extraAuthReqQueryParams: {
redirect_uri: `https://${req.headers.host}/auth/callback`,
},
})(req, res, next)
);