I am using TSED - TypeScript Express Decorators (https://tsed.io) and it replaces express code like:
server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);
With an annotated middleware class - https://tsed.io/docs/middlewares.html
So now the call to passport.authenticate()
is in the use()
method like:
@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();
}
}
And then my AuthService.authenticate()
is
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()}`);
}
My passport configuration is performed in this same AuthService class:
@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;
});
}));
}
This all works - My Azure configuration and setup for this logs in and retrieves an access_token for my API, and this token successfully authenticates and a user object is placed on the request.
HOWEVER Passport.authenticate()
seems to be asynchronous and doesn't complete until after the test for request.isAuthenticated()
. I have put in timing comments as can be seen. The after passport authenticate time: xxx
happens 2 milliseconds after the before
one.
And the after strategy done authenticate time: xxx
one happens a second after the after passport authenticate time: xxx
one.
So it looks like Async behaviour to me.
Looking in node_modules/passport/lib/middleware/authenticate.js
(https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js) there are no promises or async mentioned. However in node_modules/passport-azure-ad/lib/bearerstrategy.js
(https://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js) is an 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;
}
);
};
Could that cause async code? Would it be a problem if run in 'normal express Middleware'? Can someone confirm what I've said or to deny what I've said and to provide a solution that works.
For the record I started asking for help on this Passport-Azure-Ad problem at my SO question - Azure AD open BearerStrategy "TypeError: self.success is not a function". The problems there seem to have been solved.
Edit - the title originally included 'in TSED framework' but I believe this problem described exists solely within passport-azure-ad
.
This is a solution to work around what I believe is a problem with
passport-azure-ad
being async but with no way to control this. It is not the answer I'd like - to confirm what I've said or to deny what I've said and to provide a solution that works.The following is a solution for the https://tsed.io framework. In https://github.com/TypedProject/ts-express-decorators/issues/559 they suggest not using
@OverrideMiddleware(AuthenticatedMiddleware)
but to use a@UseAuth
middleware. It works so for illustration purposes that is not important here (I will work through the feedback shortly).Edit - I had a version that used
setInterval()
but I found it didn't work. I even tried inlining the code in to the one method so I could remove theasync
. It seemed to cause the@Post
theUserAuthMiddleware
is attached to, to complete immediately and return a 204 "No Content". The sequence would complete after this and a 200 with the desired content would be returned but it was too late. I don't understand why.