【发布时间】:2019-06-03 13:30:55
【问题描述】:
我正在使用 TSED - TypeScript Express Decorators (https://tsed.io),它替换了如下的 express 代码:
server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);
带有带注释的中间件类 - https://tsed.io/docs/middlewares.html
所以现在对passport.authenticate() 的调用是在use() 方法中,例如:
@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
constructor(@Inject() private authService: AuthService) {
}
public use(
@EndpointInfo() endpoint: EndpointMetadata,
@Request() request: express.Request,
@Response() response: express.Response,
@Next() next: express.NextFunction
) {
const options = endpoint.get(AuthenticatedMiddleware) || {};
this.authService.authenticate(request, response, next); // <-- HERE
if (!request.isAuthenticated()) {
throw new Forbidden('Forbidden');
}
next();
}
}
然后我的AuthService.authenticate() 是
authenticate(request: express.Request, response: express.Response, next: express.NextFunction) {
console.log(`before passport authenticate time: ${Date.now()}`);
Passport.authenticate('oauth-bearer', {session: false})(request, response, next);
console.log(`after passport authenticate time : ${Date.now()}`);
}
我的护照配置是在同一个 AuthService 类中执行的:
@Service()
export class AuthService implements BeforeRoutesInit, AfterRoutesInit {
users = [];
owner = '';
constructor(private serverSettings: ServerSettingsService,
@Inject(ExpressApplication) private expressApplication: ExpressApplication) {
}
$beforeRoutesInit() {
this.expressApplication.use(Passport.initialize());
}
$afterRoutesInit() {
this.setup();
}
setup() {
Passport.use('oauth-bearer', new BearerStrategy(jwtOptions, (token: ITokenPayload, done: VerifyCallback) => {
// TODO - reconsider the use of an array for Users
const findById = (id, fn) => {
for (let i = 0, len = this.users.length; i < len; i++) {
const user = this.users[i];
if (user.oid === id) {
logger.info('Found user: ', user);
return fn(null, user);
}
}
return fn(null, null);
};
console.log(token, 'was the token retrieved');
findById(token.oid, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
// 'Auto-registration'
logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
this.users.push(token);
this.owner = token.oid;
const val = done(null, token);
console.log(`after strategy done authenticate time: ${Date.now()}`)
return val;
}
this.owner = token.oid;
const val = done(null, user, token);
console.log(`after strategy done authenticate time: ${Date.now()}`);
return val;
});
}));
}
这一切正常 - 我的 Azure 配置和设置登录并为我的 API 检索 access_token,并且此令牌成功通过身份验证并将用户对象放置在请求中。
但是Passport.authenticate() 似乎是异步的,直到测试request.isAuthenticated() 之后才完成。可以看出,我已经放入了计时 cmets。 after passport authenticate time: xxx 发生在 before 之后 2 毫秒。
after strategy done authenticate time: xxx 发生在 after passport authenticate time: xxx 之后一秒。
所以对我来说它看起来像异步行为。
查看node_modules/passport/lib/middleware/authenticate.js (https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js) 没有提到任何承诺或异步。但是在node_modules/passport-azure-ad/lib/bearerstrategy.js (https://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js) 中是async.waterfall:
/*
* We let the metadata loading happen in `authenticate` function, and use waterfall
* to make sure the authentication code runs after the metadata loading is finished.
*/
Strategy.prototype.authenticate = function authenticateStrategy(req, options) {
const self = this;
var params = {};
var optionsToValidate = {};
var tenantIdOrName = options && options.tenantIdOrName;
/* Some introduction to async.waterfall (from the following link):
* http://stackoverflow.com/questions/28908180/what-is-a-simple-implementation-of-async-waterfall
*
* Runs the tasks array of functions in series, each passing their results
* to the next in the array. However, if any of the tasks pass an error to
* their own callback, the next function is not executed, and the main callback
* is immediately called with the error.
*
* Example:
*
* async.waterfall([
* function(callback) {
* callback(null, 'one', 'two');
* },
* function(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* },
* function(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
* ], function (err, result) {
* // result now equals 'done'
* });
*/
async.waterfall([
// compute metadataUrl
(next) => {
params.metadataURL = aadutils.concatUrl(self._options.identityMetadata,
[
`${aadutils.getLibraryProductParameterName()}=${aadutils.getLibraryProduct()}`,
`${aadutils.getLibraryVersionParameterName()}=${aadutils.getLibraryVersion()}`
]
);
// if we are not using the common endpoint, but we have tenantIdOrName, just ignore it
if (!self._options._isCommonEndpoint && tenantIdOrName) {
...
...
return self.jwtVerify(req, token, params.metadata, optionsToValidate, verified);
}],
(waterfallError) => { // This function gets called after the three tasks have called their 'task callbacks'
if (waterfallError) {
return self.failWithLog(waterfallError);
}
return true;
}
);
};
这会导致异步代码吗?如果在“普通快递中间件”中运行会不会有问题?有人可以确认我所说的或否认我所说的并提供有效的解决方案。
为了记录,我开始在我的 SO 问题 -Azure AD open BearerStrategy "TypeError: self.success is not a function" 寻求有关 Passport-Azure-Ad 问题的帮助。那里的问题似乎已经解决了。
编辑 - 标题最初包含“在 TSED 框架中”,但我相信所描述的这个问题仅存在于 passport-azure-ad 中。
【问题讨论】:
-
我尝试在执行
if (request.isAuthenticated())代码之前添加一个超时,它确实有效。 -
噢噢噢噢,我不是说我解决了问题。以上
setTimeout是一个hack,证明所讨论的问题是我完成这项工作所剩下的一切。 -
这是我的问题,我投票决定关闭它,因为它变得过于杂乱无章且不清楚。我打开了stackoverflow.com/questions/56453040/…。
标签: node.js express azure-active-directory passport.js adal