I am struggling with how to get my user decrypted data for the current user, basicly everytime a user does login he get a token at the moment.
After i login i can capture a phote and send it to the server, following my code you guys can see that this request needs a token to work.
Basicly i have a problem related to my app.js(starting file) i try to set a app.use that needs a token for all the routes that comes after the register and login, like this:
app.use('/',require('./routes/index'));
app.use(jwtPermission);
router.use('/fotos',fotos);
my jwt permission file:
var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');
module.exports = function(req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
console.log(req.headers['x-access-token']);
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token,jwtConfig.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
router index(connection to authentication and fotos files)
var express = require('express');
var router = express.Router();
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date());
console.log('Request Type:', req.method);
console.log('Request URL:', req.originalUrl);
next(); //passa a solicitação para a próxima função de middleware na pilha
});
router.use('/',require('./authentication'))
router.use('/fotos',require('./fotos'));
router.use(function(req,res,next){
return res.status(404).json({Error:"Invalid Url"});
})
module.exports = router;
when i point to /fotos it doesn't enter the jwtPermission as i want, what is wrong?
you can add your token validation middleware before function that handles some route. For example:
router.use('/fotos', jwtAuthentication, require('./fotos'));
Related
I am trying to implement Passport.js Google Login to my MERN.
But, I have this middleware:
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = async function(req, res, next) {
// Get token from header
const token = req.header("x-auth-token");
// Check if not token
if (!token) {
return res.status(401).json({ msg: "No token, authorization denied" });
}
// Verify token
try {
await jwt.verify(token, config.get("jwtSecret"), (error, decoded) => {
if (error) {
res.status(401).json({ msg: "Token is not valid" });
} else {
req.user = decoded.user;
next();
}
});
} catch (err) {
console.error("something wrong with auth middleware");
res.status(500).json({ msg: "Server Error" });
}
};
As you can see, JWT is asking for token because I made JWT auth before.
What should I write on my Google Login callback? Should I write JWT on Callback? Does this make sense?
router.get(
"/google/redirect",
passport.authenticate("google"),
async (req, res) => {
//here
}
);
I had the same problem.
I found the suggestion: redirect to the expected page with a cookie which holds the JWT.
Link here: Facebook-passport with JWT
However, if we store the jwt token in a cookie, then we cannot use the api for the mobile app.
I am trying to build an authentication system so, i used node , mysql,express for that so now i am simply saving and checking user exist in database can access but now i added JWT to it, so now i want this JWT token to store in localstorage or in cookies so, can someone guide me how can i do so
this is my authentication controller.js
var Cryptr = require('cryptr');
cryptr = new Cryptr('myTotalySecretKey');
var express = require('express');
const ap = express();
var jwt = require('jsonwebtoken');
var connection = require('./../config');
module.exports.authenticate = function (req, res) {
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields) {
if (error) {
res.json({
status: false,
message: 'there are some error with query'
});
} else {
if (results.length > 0) {
decryptedString = cryptr.decrypt(results[0].password);
if (password == decryptedString) {
jwt.sign({ email, password },
'secretkey',
{ expiresIn: '10days' },
(err, token) => {
console.log('token:' + token);
module.exports = token;
console.log(token);
res.redirect('/home.html');
}
);
} else {
res.redirect('/login.html');
console.log("Wrong Input");
}
}
else {
res.redirect('/login.html');
}
}
});
};
now i want to pass the token value to the local-storage or cookies so that i can restrict someone from acessing a page, i am reallly new to node js so any help would be appriciated
First I should notify you that do not put any secret things like password in jwt payload because the values of the payload could be accessed easily, you can try to copy paste a jwt in jwt.io site and see the payload.
set jwt in cookie like below, this will use express cookie method that does set Http Set-Cookie header:
res.cookie('jwt', generated_cookie)
.redirect('/home.html');
Also if you want to use localStorage you can set jwt in header and then in your code get the jwt from the header of login request and save it in localStorage and after that you should pass it as header in all other request, but this approach is a better solution for api calls like when you use react or vue ...
res.set({x-token: generated_token});
// In your code get
// get token from response
localStorage.setItem('token', token);
// now whenever calling api pass token as header
I show you one solution using jwt token, you choose another way:
Back-end file e.g. api.js
let jwt = require('jsonwebtoken')
let secret = 'yourSecret'; //secret key necessary to encode token
let Cryptr = require('cryptr');
let cryptr = new Cryptr('myTotalySecretKey');
module.exports = function(router,upload) {
function tokenAuth(req, res, next){
let token = req.body.token || req.body.query || req.headers['x-access-token']
if(token){
jwt.verify(token, secret, function(err,decoded){
if(err){
res.json({ authenticated: false, message:'Invalid token'})
} else {
req.decoded = decoded;
next()
}
})
} else {
res.json({success:false, message:'No token provided'});
}
}
router.post('/authenticate', function(req, res){
connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields){
if(error) {
res.json({ success:false, message: err })
}
if(!results.length){
res.json({success:false, message:'User no found'})
} else if (results.length>0){
if(!req.body.password){
res.json({success:false, message:'Password was not provided'});
} else {
var validPassword = cryptr.decrypt(results[0].password);
if(validPassword === req.body.password){
res.json({success:false, message:'Incorrect password'})
} else {
var token = jwt.sign({username: results[0].username, email: results[0].email}, secret, {expiresIn: '24h'})
res.json({success:true, message:'You have logged in correctly!', token: token })
}
}
}
})
})
//If you want create a route for authenticated users for example comment posts, you can use our `tokenAuth function`
router.post('/post/comment',tokenAuth,function(req,res){
//access only for authenticated users
}
return router
}
This tokenAuth function we'll be use in paths restricted to authenticated users
server file e.g. server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 80;
const http = require('http').Server(app);
const routes = require(path_to_api.js)(router);
app.use('/myApi', routes)
//***Here you should implement more details about your project such as routes, body parsers and other middlewares*****//
//Connect to your database
http.listen(port, ()=> console.log(`Server running on ${port}`))
Front-end file e.g. controller.js
function(login){
return fetch('/myApi/authenticate',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(login)
}).then(result=>result.json()).then(data=> window.localStorage.setItem('token', data.token))
}
//`login` argument should be an object and should be like {username: 'user username', password: 'user password'}
In order to make a user store cookies, you can use the Set-Cookie header. From MDN:
Set-Cookie: <cookie-name>=<cookie-value>
In order to pass a header using Express, you can use res.set(), e.g. res.set("Set-Cookie", "Token=" + token). I also suggest you use the HttpOnly cookie directive, since it seems from your post that you don't access this token directly via Javascript and you simply want to check it when the client requests a webpage: res.set("Set-Cookie", "Token=" + token + "; HttpOnly").
The client will send the Cookie header to you when it requests a resource. You can check this header using req.header('Cookie'), and the output will be "Token=<token>" if the user is authenticated. You can then check this token for authenticity.
Hello I am working on mock authentication in nodeJs using express framework.I am using passport-jwt and jasonwebtoken for authentication. I created api and working well on postman.But I stuck on front end side I am not able to use protected api's on front end side.In postman i send token using headers and it works well.But it does not work on front end side.How to send token and verify from front end side??
My code is:
app.post("/login", function(req, res) {
if(req.body.name && req.body.password){
var name = req.body.name;
var password = req.body.password;
}
var user = users[_.findIndex(users, {name: name})];
if( ! user ){
res.status(401).json({message:"no such user found"});
}
if(user.password === req.body.password) {
var payload = {id: user.id};
var token = jwt.sign(payload, jwtOptions.secretOrKey);
res.json({message: "ok", token: token});
} else {
res.status(401).json({message:"passwords did not match"});
}
});
and if token is valid this post method should redirect to this page
app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
res.json("Success! You can not see this without a token");
});
npm install cookie-parser
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(function (req, res, next) {
var cookie = req.cookies.jwtToken;
if (!cookie) {
res.cookie('jwtToken', theJwtTokenValue,
{ maxAge: 900000, httpOnly: true });
} else {
console.log('let's check that this is a valid cookie');
// send cookie along to the validation functions...
}
next();
});
I have a aplication where the user can take some pictures and send to the database, just as simple as that.
Everytime the user login he get a token, if everything fine with the token(he doesn't need to login).
I followed this tutorial to do the jwt authentication, now i want to check on every request except(/login / register) that token and decode it to get the user info ( i am just saving the username, its unique so its fine).
So imagine i am routing to /flower?flowerName (random route) so in this route i want to create a register and save in my database some data, but before that as i said, i should enter a middleware that checks the permission.
This is my middleware:
var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');
module.exports = function(req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
console.log(req.headers['x-access-token']);
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token,jwtConfig.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
console.log("HEREE");
// if everything is good, save to request for use in other routes
req.decoded = decoded;
console.log(req.decoded);
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
my problem is, how can i get the userID for my middleware and then save it in my next route? can i pass it trough the next? like next(userID)????
How can i get the parameter then.
this is where i save the register:
var express = require('express');
var User = require('../models').User;
var Foto = require('../models').Foto;
var router = express.Router();
var jwt = require('jsonwebtoken');
var fs = require('fs');
var fsPath = require('fs-path');
module.exports = {
sendPicture: function (req, res,next) {
var bitmap = new Buffer(req.body.base64, 'base64');
var dummyDate = "25/04/14-15:54:23";
var lat = req.params.lat;
var lon = req.params.lon;
var alt = req.params.alt;
var path = __dirname + "/../public/images/" + req.params.flowerName + "/example3.png";
var fotoPath = ""
var userId = 1;
console.log(lat);
console.log(lon);
console.log(alt);
console.log(req.query.token);
fsPath.writeFile(path, bitmap, function (err) {
if (err) {
console.log(err.stack);
return err;
}
Foto.create({
image: path,
userId: userId
}).then(function () {
return res.status(200).json({ message: "foto created" });
}).catch(function(err){
console.log(err.stack);
})
});
}
}
You should be able to pass any state variables through the whole chain through res.locals, i.e.
res.locals.decoded = decoded;
next();
you can find the details on res.locals here
I am using nodejs and sequelize to create simple user registration, I already did the login and register, but when login is a success I don't get any token.
I have tried to console.log the token to see if I get some result, but there is no response in the console related to the token.
Here is my code:
var express = require('express');
var User = require('../../models').User;
var router = express.Router();
var jwt = require('jsonwebtoken');
var app = require('../../app');
/*var token = jwt.sign(user, app.get('superSecret'), {
expiresInMinutes: 1440 // expires in 24 hours
});*/
router.post('/', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for login" });
}
// search a user to login
User.findOne({ where: { username: req.body.username} }) // searching a user with the same username and password sended in req.body
.then(function (user) {
if (user && user.validPassword(req.body.password)) {
//return res.status(200).json({ message: "loged in!" }); // username and password match
// create a token
var token = jwt.sign(user, app.get('superSecret'), {
expiresInMinutes: 1440 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
else{
return res.status(401).json({ message: "Unauthorized" }); // if there is no user with specific fields send
}
}).catch(function (err) {
return res.status(500).json({ message: "server issues when trying to login!" }); // server problems
});
});
module.exports = router;
You should use express-jwt library. https://www.npmjs.com/package/express-jwt
It's middleware for express. Example:
var jwt = require('express-jwt');
app.get('/protected',
jwt({secret: 'shhhhhhared-secret',
credentialsRequired: false,
getToken: (req) => req.cookies.id_token // when cookies are using. 'id_token' is cookie's name
}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
Also you may write as app.use(...) or app.anyRequest(...)