Comments (11)
You can check for Error string in info to catch and provide custom messages.
passport.authenticate('jwt', (error, user, info) => {
sails.log.info('isAuthenticated policy: ', error, user, info.name);
if (info.name === 'TokenExpiredError') info.status = 401;
if (info.name === 'JsonWebTokenError') info.status = 401;
if (info.name === 'Error') info.status = 401;
if (error || !user) return res.negotiate(error || info);
req.user = user;
next();
})(req, res);
from passport-jwt.
I think you're looking for the Custom Callback functionality of the Passport module.
from passport-jwt.
Sure, I can go and check if the authorization header exists before triggering the passport middleware. But why don't we put it into the strategy extraction method itself? Something like:
jwtFromRequest: ExtractJwt.fromAuthHeader({failmessage: 'missing token'})
from passport-jwt.
This is not the point of the extractor function and a violation of single responsibility pattern. The extractor function is only responsible for extracting the JWT from the request if it exists.
There is no need to check the request for the authorization header before triggering passport. The decision of what to do if the JWT is missing takes places in the strategy's authenticate() method.. Right now it returns a generic error which you can then catch and handle in the custom callback register via passports Custom Callback functionality.
That is where I recommend providing the custom error response.
The potential improvements I see in this area are:
- Return a custom error class to make it easier to identify when the JWT was missing.
- Do something like passport-local and provide a custom error message via the Strategy constructors generic options argument.
from passport-jwt.
Let me know if this covers your use case. If you have a suggestion I am open to pull requests or we can create a feature request to address the need.
Thanks for using the module and I appreciate any feedback!.
from passport-jwt.
Haven't heard anything in a few days. Closing for now.
from passport-jwt.
Hello. Cannot understand how to set custom error message for different errors and how can I embed JWT black list to this strategy? Thanks for answer
from passport-jwt.
@GeekEdem Sorry to sound like a broken record but handling custom error messages is explained here: http://passportjs.org/docs#custom-callback
and if you want to blacklist JWTs you can put that logic into the verify
callback when constructing the strategy
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
if ( is_jwt_blacklisted(jwt_payload) ) {
return done(err, false);
}
else {
// jWT is not blacklisted, look up a user or
// whatever else you were planning on doing with a
// valid JWT
}
});
note that is_jwt_blacklisted
is just a funciton I made up. You'll have to supply that function as the strategy doesn't maintain a blackisted jwt list on its own.
from passport-jwt.
@themikenicholson Here is my solution, if someone need)
function requireAuth (req, res, next){
passport.authenticate('jwt', jwtSession, function (error, decryptToken, jwtError) {
if(typeof (jwtError) === 'object'){
return general.response(res, {
field: 'Authorization',
location: 'header',
messages: [
jwtError.message
]
});
} else if (!error) {
let token = req.header('Authorization').slice(4);
TokenModel.findOne({token: token}).lean().exec( (err, result) => {
if(!err && !result) {
req.user = decryptToken;
return next();
} else if (!err && result) general.response(res, {
field: 'Authorization',
location: 'header',
messages: [
'token is in black list'
]
});
else general.response(res, err);
});
}
})(req, res, next);
}
this method I use as middleware in express.
general.response
- this is method, that make response message and return them.
TokenModel
- this is mongoose model, to check is token in blacklist collection in MongoDB.
from passport-jwt.
@themikenicholson
Following the passport custom-callback
router.get('/jwt', (req, res, next) => {
passport.authenticate('jwt', (err, user, info) => {
if (err) return next(err); // It is null
if (!user) return res.status(403).json(info);
res.status(200).json(user);
})(req, res, next);
});
If token extraction failed, the custom error is placed in the "info" parameter. Is this by design? Shouldn't it be at the "err" parameter?
Update: I will continue with Issue #75
from passport-jwt.
Manteiners should add this "info" param and examples to the http://www.passportjs.org/packages/passport-jwt/ docs. I could't find the error until i read this issue. Thanks
from passport-jwt.
Related Issues (20)
- Refresh_token HOT 3
- How to set Token Bearer in the authorization header? HOT 4
- Multiple JWKS URIs HOT 4
- "TypeError: JwtStrategy requires a secret or key" with NestJS HOT 5
- Disallow None algorithm by default HOT 6
- Project Status HOT 8
- Passport-jwt extractor fromUrlQueryParameter don't handle handshake requests (websocket) HOT 1
- I'm always unauthorized. HOT 2
- How to ignore ignoreExpiration for a specific endpoint? HOT 1
- Add Custom extractor which takes JwtFromRequestFunction as argument HOT 1
- Provide own jwt-verify option HOT 1
- Is cookieExtractor buggy?
- How to create new jwt Token HOT 1
- vulnerability in passport-jwt's dependancy jsonwebtoken HOT 7
- JWT verification for auth code or PKCE flow HOT 1
- jsonwebtoken update to ^9.0.0 in [email protected] was a breaking change HOT 1
- [email protected] > [email protected] vulnerability HOT 1
- TypeError: JwtStrategy requires a secret or key getting this error while running in node.js
- Passport authentication with JWTStrategy not working even jwt is not getting called even the console.log({ jwt_payload }); is not getting called HOT 1
- use `request.header(AUTH_HEADER)` instead of `request.headers[AUTH_HEADER]`
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from passport-jwt.