passport-http-bearer icon indicating copy to clipboard operation
passport-http-bearer copied to clipboard

Unable to send custom messages from passport.authenticate in route

Open shajunr88 opened this issue 6 years ago • 1 comments

I had implemented passport-http-bearer for authentication and upon token expiry i need to send token expired message from my rest api.For that I throw a message from BearerStrategy .But from the library it throws only 'Unauthorized' message. `passport.use(new BearerStrategy( function(accessToken, done) {

    AccessToken.findOne({where:{token:accessToken}}).then((token) => {
        if (!token) { 
            return done(null, false); 
        }  
        
        if( Math.round((Date.now()-token.created_at)/1000) > config.expireTime ) {
            AccessToken.destroy({where:{token: accessToken}}).catch(err =>{console.log(err);return done(err);});
            return done(null, false, { message: 'Token expired' });
        }
        User.findById(token.user_id).then((user)=>{
            if (!user) { 
                return done(null, false, { message: 'Unknown user' }); 
            }
            var info = { scope: '*' };
            done(null, user, info);
        }).catch(err => {console.log(err);return done(err); })

    }).catch(err=>{console.log(err);return done(err);});`

And the api route is app.get(version+'/grids',passport.authenticate('bearer', { session: false }),gridsController.list); How to get the token expired message instead of 'Unauthorized' message

shajunr88 avatar Feb 16 '18 05:02 shajunr88

Have you verified the "Token expired" branch is run? I'd dive in deeper if you could provide a minimal runnable example (maybe as a gist). Another minor performance hint: I'd calculate the token expiration date in milliseconds, save that, and then just compare it to Date.now() in each check, since the check operation is probably performed lots more times.

Update:

from the library it throws only 'Unauthorized' message.

I guess you mean the "HTTP/1.1 401 Unauthorized" status code? That's a standardized part of the protocol. The place for custom messages would be in the error response body, which might be generated by later middleware using the data in req.authInfo.

You could also try providing a custom error as the first arument to done.

mk-pmb avatar Feb 16 '18 14:02 mk-pmb