Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to send custom messages from passport.authenticate in route #55

Open
shajunr88 opened this issue Feb 16, 2018 · 1 comment
Open

Comments

@shajunr88
Copy link

shajunr88 commented Feb 16, 2018

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

@mk-pmb
Copy link

mk-pmb commented Feb 16, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants