With koa.js and koa-passport, can I apply middleware conditionally?
My server authenticates web visitors using koa-passport with the built-in 'session' authentication:
app.use( passport.initialize() );
app.use( passport.authenticate( 'session', {} ); // = app.use( passport.session() );
Now I need to access the server as an API end point, also via the SSL port. An API end point doesn't use sessions; authentication is by bearer token. Passport-http-bearer does this:
app.use( passport.initialize() );
app.use( passport.authenticate( 'session', {} );
app.use( passport.authenticate( 'bearer', {session:false} ));
This doesn't work, of course, because either 'session' or 'bearer' will always fail, so no request gets through.
I thought of applying the middleware conditionally:
if( this.request.headers.authenticate.startsWith( 'Bearer' )){
app.use( passport.authenticate( 'bearer', {session:false} ));
} else {
app.use( passport.authenticate( 'session', {} );
}
That doesn't work, of course, because the stack is not built for each request at runtime, so the request headers are undefined and it won't compile.
I tried koa-unless; in theory it should work, but even the sample code throws an error on koa@1.2.
So at the moment I have the condition patched into the passport-http-bearer strategy; this works, but it's pretty much unsupportable.
Any ideas? Thanks!