nodejs jwt verify always fails - node.js

any idea why this test code always prints fail, I designed this code to figure out what is wrong with my authentication server for my school project and I wrote this to always verify but it never does
var refreshToken = jwt.sign({username: "test",}, "secret");
const tokenARR = refreshToken.split('.');
const signiture = tokenARR[2];
jwt.verify(signiture, "secret", (err, user) => {
if (err) {
console.log("fail");
}
else {
console.log("TEST");
}
})

Yes, the 3rd part of a JWT token is signature. But the jwt.verify function verify and decode the token at the same time.
So it must be jwt.verify(refreshToken) instead of jwt.verify(signiture)

Related

Why is 'currentUser' and 'onAuthStateChanged' in firebase always null?

What I want to achieve
A user, who logged in or signed up should not re-login after one hour. The restriction of one hour comes from firebase authentication, if not prevented (what I try to accomplish).
Problem
After a user is logged in via firebase authentication (signInWithEmailAndPassword) I always get null for currentUser and onAuthStateChanged.
What I tried
I'm using React (v17.0.2) using 'Create React App'. On server side I'm using NodeJS (v12). The communication between both is accomplished using axios (v0.21.1)
First I tried to send the token stored in localStorage, which came from firebase (server side), back to the server. But the server tells me, that the token is no longer valid. Server side code as follows:
module.exports = (request, response, next) => {
let idToken;
if (request.headers.authorization && request.headers.authorization.startsWith('Bearer ')) {
idToken = request.headers.authorization.split('Bearer ')[1];
console.log("idToken:", idToken);
} else {
console.error('No token found');
return response.status(403).json({ error: 'Unauthorized' });
}
admin
.auth()
.verifyIdToken(idToken)
.then((decodedToken) => {
console.log('decodedToken', decodedToken);
request.user = decodedToken;
return db.collection('users').where('userId', '==', request.user.uid).limit(1).get();
})
.catch((err) => {
console.error('Error while verifying token', err);
return response.status(403).json(err);
});
};
After that I tried the following code on client side.
handleSubmit = () => {
const userData = {
email: this.state.email,
password: this.state.password
};
axios
.post(firestoreUrl() + '/login', userData)
.then((resp) => {
console.log("token:", resp.data); //here I get a valid token
localStorage.setItem('AuthToken', `Bearer ${resp.data.token}`);
console.log("firebase.auth().currentUser:", firebase.auth().currentUser); //but this is null
})
.then((data) => {
console.log(data);
console.log("firebase.auth().currentUser:", firebase.auth().currentUser); //still null
})
.catch((error) => {
console.log("Error:", error);
});
};
What irritates me is that I get a token from firebase (server side), the token is then stored in localStorage (client side) but firebase then tells me, that the currentUser is null. But presumably they are not mutually dependent =/.
I'm able to access all secured sites in my app. I can log out and in again. But whatever I do the currentUser is null.
I also tried to run the code above in componentDidMount()-method. But no success.
I tried an approach from this link (hopefully in a way it should be), but it didn't work. Still getting null for both currentUser and onAuthStateChanged if I implement following code.
firebase.auth().onAuthStateChanged(user => {
if (user) {
console.log("state = definitely signed in")
}
else {
console.log("state = definitely signed out")
}
})
I always get logged to the console, that the user is 'definitely signed out'.
During research I noticed that the point at which I should try to get the currentUser-Status is kind of tricky. So I guess that one solution is to implement the currentUser-code at another/the right place. And here I'm struggling =/.
As I found out at a similar question here on SO, I did a bad mistake. Apparently, it's not a good idea to perform the signIn- or createUser-functionality on server side. This should be done on client side. In the question mentioned above are some good reasons for doing that on server side but in my case it's quite ok to run it on client side.
Thanks to Frank van Puffelen for leading the way (see one of the comments in the question mentioned above).

How do I pass authentication tokens/headers?

I have designed an authentication function that works perfectly when tested via my POSTMAN endpoint. This is what it looks like when the Authorization value is correct:
And this is what it looks like when I alter the Authorization value to deliberately fail the authorization process:
Find below the authorization code:
const jwt = require ('jsonwebtoken');
const authenticate = (req, res, next)=>{
try {
const token = req.headers.authorization.split(' ')[1]
const decode = jwt.verify(token, 'verySecretValue')
console.log('Authentication PASSED!');
next();
}
catch (error) {
res.json({
message: 'Authentication FAILED!'
})
}
}
module.exports = authenticate
And, now find below the code I use to render:
.
.
.
const authenticate = require('./authentication/authenticate.js');
.
.
.
.
app.get('/list', authenticate, async (req,res)=> {
let countyResult = await county();
let transId = await transactionId();
transModel.find({transIndustry: 'Pharmacy'}, (err, docs)=> {
if (!err)
{
res.render('list', {data : docs, countyName: countyResult, transId: transId});
}
else
{
// res.status(status).send(body);
}
})
});
However, when I try to access the endpoint/link/address above via the browser, I get this error message:
{"message":"Authentication FAILED!"}
I feel like this is an Authorization value issue, and I don't quite know how I should be passing this value when rendering the list page via res.render('list', {data : docs, countyName: countyResult, transId: transId});.
Looking forward to your help.
You may inspect the requests that your browser makes by opening the dev tools and going to the network tab. There, you can check if the correct header is passed.
Do you have any code in the frontend to pass the token in the header?
If that's not an option, you may explore setting the token in a cookie. This way, you are sure that every request to your backend will include it.

How can you verify if a JWT is still valid?

I want to make a call every X amount of minutes from the client side to see if the JWT is still valid. I'm not sure how to do this in nodeJS. If I'm already authorized, how can i check if I'm still authorized.
An elegant solution to handle token expiration is when you set the token(in LocalStorage or store(redux), or both) is also to have an Async function that runs exactly when the token expires. Something like this:
const logUserOut = token =>{
setTimeout(()=> MyLogoutFunction(), token.expiresIn)
}
This way you make sure that the user won't be logged when the token is no longer valid.
You can have your client side decode the JWT and check an expiry field and compare it with system time.
eg.
isExpired: (token) => {
if (token && jwt.decode(token)) {
const expiry = jwt.decode(token).exp;
const now = new Date();
return now.getTime() > expiry * 1000;
}
return false;
you can use npm install jsonwebtoken or some other npm package on the client side to do this
Create and endpoint that verifies the token is valid. You can use the the jsonwebtoken package.
import jwt from 'jsonwebtoken';
const verifyToken = (req, res) => {
const token = req.headers.authorization;
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).send();
}
// can do something with the decoded data
})
}
router.post('/verify-token', verifyToken);
I found a better option with promise to check if my token is valid
jwt.verify(token,key,(err,result)=>{
if(err){
if(err.name == "TokenExpiredError"){
console.log("Expired") //This case is when token expired
}
else{
console.log(err.name) //Any other case
}
}
else{
//Here code for your promise using 'result' when token is Valid
}
})
EDIT: this code is OK if you don't use the JWT for security reason, only if you use it to public stuff.
since this request is show to user if it valid or not, and if not why.
I'm using it only to understand if object is still available for other reason. (and it's OK to be public)

Passport-jwt authenticate not working well with node-jwt-simple

I'm using passport-jwt to authenticate some routes and I'm creating my jwts with node-jwt-simple/jwt-simple but facing some difficulties cause it looks like my passport-jwt authenticate middleware is not being called at all.
Here is my
passport-jwt-strategy
const jwtOpts = {
jwtFromRequest: ExtractJwt.fromHeader('Authorization'),
secretOrKey: secret,
};
passport.use(new jwtStrategy(jwtOpts, (payload, done) => {
console.log('payload ', payload.sub);
User.findById(payload.sub, (err, user) => {
if(err) { return done(err); }
if(!user) { console.log('didnt find!'); return done(null, false); }
done(null, user);
});
}));
which i'm then integrating it over here.
routes file
router.get('/success',
passport.authenticate('jwt', {session: false}),
async (ctx, next) => ctx.body = await "success!");
Here is also the way I make my jwt.
function tokenForUser(user) {
const timeStamp = new Date().getTime;
return jwt.encode({sub: user._id, iat: timeStamp}, secret);
}
//- Later in signup process
userToSave.save(async(err, user) => {
if(err) { return next(err); }
const token = await tokenForUser(user);
next(token);
});
//- If this helps, here is how my secret file looks like.
const secret = "JKAha23ja1ddHdjjf31";
export default secret;
Problem comes, when I hit that route i only get Unauthorized and in the console nothing gets logged out not even the 'payload' key I specified first.
I should also say that I have the token at ctx.request.get('Authorization') (Koa based) i think it's something like req.header('Authorization') with express in all routes.
Also The exact express based problem can be found on the github issues of node-jwt-simple here incase there is any problem with my code samples.
Thank you.
After I wrapped my head right i knew that this has been my horrible understanding of how the whole authentification process works.
When I decoded the token from ctx.get('Authorization') I got a different _id than the one stored in the db Because I had hardcoded Authorization header in postman and thought "If I ctx.set('Authorization', token); It will replace the one I hardcoded on postman".
Less did I think that this jwt will be included in a header of requests when I make http calls on front end.
I naively thought jwts are passed directly from the server to the browser (Something like how render works) and Not from the server to an ajax process which later embeds it in request made which is the correct way.
The whole code is awesome, except now I have to just pass the token ctx.body = token; after I created it when I signed up.
Thank You.

Node/Express - Good approach to secure communication between client/server

I'm building a backend API with Node/Express, which get the data from a MongoDB. The front will be written in React.
I would like to secure the communication client/server, but I don't know how I have to think about the process.
I see many tutorial about passport or JWT, but this is good for an user authentication.
I don't know if creating a token for every request based on the time (for example) is a good approach or it's too consuming for a web app.
But my goal is to secure the data because even if the API is private you can easily find out the route and try to figure it out how to fake request with Postman or something else to scrap the data.
The accepted standard is to use a fixed API KEY. This peace of info should be a randomly generated string that you send in each request in the header. Your server has to check the HTTP request each time to see if the API KEY is present in the header, and if it is, then it has to check against the stored value in the environment variable (never store the API KEY in code).
If the API KEY gets compromised, then you can easily update the env variable, and you are good again.
Now, this solution will be pointless without a HTTPS connection, because anyone will be able to sniff the traffic and see the API KEY. An encrypted connection is a must in this case.
This approach is used by virtually every company that has a public API: Twitter, Facebook, Twilio, Google etc.
Google for example has an extra step where they give you a token that will expire, but this will be an over kill in your case: at least in the beginning.
The following code is an example of my implementation of a API KEY check
app.use(function(req, res, next) {
//
// 1. Check if the APIKey is present
//
if(!req.headers.authorization)
{
return res.status(400).json(
{
message: "Missing APIKey.",
description: "Unable to find the APIKey"
}
);
}
//
// 2. Remove Basic from the beginning of the string
//
let noBasic = req.headers.authorization.replace('Basic ', '');
//
// 3. Convert from base64 to string
//
let b64toString = new Buffer(noBasic, 'base64').toString("utf8");
//
// 4. Remove the colon from the end of the string
//
let userAPIKey = b64toString.replace(':', '');
//
// 5. Check if the APIKey matches the one on the server side.
//
if(userAPIKey != process.env.API_KEY)
{
return res.status(400).json(
{
message: "APIKey don't match",
description: "Make sure what you are sending is what is in your server."
}
);
}
//
// -> Go to the next stage
//
next()
});
You can check the whole file with the whole implementation hear.
As I just finished the auth part of my AngularJS application. The answer will be JWT and Passport, you should use the great technologies to protect your data / API.
If you use the JWT library, it will help you hold the http heads for authorization.
Some of the code I used:
app.js
var jwt = require('express-jwt');
var auth = jwt({
secret: config.jwt.secret,
userProperty: 'payload'
});
app.use('/api/secret', auth, apiSecretRoutes);
login.js
module.exports.login = function (req, res) {
if (!req.body.username || !req.body.password) {
return tools.sendJSONresponse(res, 400, {
message: 'All fields required!'
});
}
passport.authenticate('local', function (err, user, info) {
var token;
if (err) {
return tools.sendJSONresponse(res, 404, err);
}
if (user) {
token = user.generateJwt();
return tools.sendJSONresponse(res, 200, {
ok: true,
message: 'welcome ' + user.name,
token: token
});
} else {
return tools.sendJSONresponse(res, 400, info);
}
})(req, res);
};
user.js
userSchema.methods.generateJwt = function() {
var expiryDays = 1;
var expiry = new Date();
expiry.setDate(expiry.getDate() + expiryDays);
return jwt.sign({
_id: this._id,
username: this.username,
name: this.name,
exp: parseInt(expiry.getTime() / 1000)
}, config.jwt.secret);
};
More Refs:
https://thinkster.io/angularjs-jwt-auth
http://devdactic.com/restful-api-user-authentication-1/
http://devdactic.com/restful-api-user-authentication-2/
http://jwt.io
https://github.com/auth0/express-jwt

Resources