当直接在路由器设置中使用 passportJS 方法时,请求/响应/下一个功能会“神奇地”从关闭中消耗掉。
因此,如果您将它们提取并应用到另一个类中,您将需要明确地提供它们。
在路由器类中
...
this.router.get('/login', (req, res, next) => this.authenticate(req, res, next)); // Called by user
this.router.get('/callback', (req, res, next) => this.callback(req, res, next)); // Called by OAuth2 provider
...
/**
* Authenticate the user
* @param req
* @param res
* @param next
*/
private authenticate(req: Request, res: Response, next: NextFunction){
this.logger.debug('Performing authentication');
this.customController.authenticate(req, res, next);
}
/**
* Callback after OAuth2 provider has authenticated the user
* @param req
* @param res
* @param next
*/
private callback(req: Request, res: Response, next: NextFunction){
this.logger.debug('Callback from OAuth provider');
this.customController.callback(req, res, next);
}
在自定义控制器中
/**
* Executes the authentication using passportJS
*/
public executeAuthenticate(req: Request, res: Response, next: NextFunction): void {
this.logger.debug('Authenticate using passport');
passport.authenticate('<strategy>', { scope: ['email', 'profile'] })(req, res, next); // <== Here! See that the function is called using the parameters (req,res,next)
}
/**
* Callback after login completion
* @param req
* @param res
* @param next
*/
public callback(req: Request, res: Response, next: NextFunction): void {
this.logger.debug('Callback from oAuth provider');
// Ask passportJS to verify that the user is indeed logged in
passport.authenticate('<strategy>', (err, user, info)=> {
this.logger.debug('Authentication check done');
if (err) {
this.logger.debug('Authentication error');
return next(err);
}
if (!user) {
this.logger.debug('Could not extract user');
return next('Could not find user object');
}
this.logger.debug('Authentication succeeded');
return res.json(user);
})(req, res, next); // <== Here! See that the function is called using the parameters (req,res,next)
}