Using koa, can I apply passport middleware conditionally?
<p>With koa.js and koa-passport, can I apply middleware conditionally?</p>

<p>My server authenticates web visitors using koa-passport with the built-in 'session' authentication:</p>

<pre><code>app.use( passport.initialize() );
app.use( passport.authenticate( 'session', {} );  // = app.use( passport.session() ); 
</code></pre>

<p>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:</p>

<pre><code>app.use( passport.initialize() );
app.use( passport.authenticate( 'session', {} );
app.use( passport.authenticate( 'bearer', {session:false} ));
</code></pre>

<p>This doesn't work, of course, because either 'session' or 'bearer' will always fail, so no request gets through.</p>

<p>I thought of applying the middleware conditionally:</p>

<pre><code>if( this.request.headers.authenticate.startsWith( 'Bearer' )){
    app.use( passport.authenticate( 'bearer', {session:false} ));
} else {
    app.use( passport.authenticate( 'session', {} );
}
</code></pre>

<p>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.</p>

<p>I tried koa-unless; in theory it should work, but even the sample code throws an error on koa@1.2.</p>

<p>So at the moment I have the condition patched into the passport-http-bearer strategy; this works, but it's pretty much unsupportable.</p>

<p>Any ideas?  Thanks!</p>