I want to make a middleware to check the user. I'm using JWT and cookies for this. I retrieved the cookie and decrypted it (it has been encrypted in the login controller function). Then I used jwt.verify(). But I've received this error message : JsonWebTokenError: jwt malformed.
I've seen that it may mean that the token wasn't "the right formated" one. But I can't figure it out.
checkUser function :
exports.checkUser = async(req, res, next) => {
const cryptedToken = req.cookies.snToken;
console.log("cryptedToken01", cryptedToken); //displays a string consists of 3 parts, separated by /
const token = cryptojs.AES.decrypt(cryptedToken, process.env.COOKIE_KEY).toString();
console.log("token01", token); // displays a longer monolithic string
if (token) {
jwt.verify(token, process.env.COOKIE_KEY, async(err, verifiedJwt) => {
if (err) {
console.log("err inside jwt verify", err); // displays an error mesassage (JsonWebTokenError: jwt malformed)
console.log("res.locals", res.locals); //displays res.locals [Object: null prototype] {}
res.locals.user = null;
res.cookie("snToken", "", { maxAge: 1 });
next();
} else {
let user = await User.findByPk(verifiedJwt.userId);
res.locals.user = user;
next();
}
});
} else {
res.locals.user = null;
next();
}
};
my login function :
exports.login = async(req, res) => {
try {
const user = await User.findOne({ where: { email: req.body.email } });
if (!user) {
return res.status(403).send({ error: 'The login information (email) is incorrect!' });
}
bcrypt
.compare(req.body.password, user.password)
.then((isPasswordValid) => {
if (!isPasswordValid) {
return res.status(403).send({ error: 'The login information (pwd) is incorrect!' });
} else {
const newToken = jwt.sign(
{ userId: user.id },
process.env.COOKIE_KEY, { expiresIn: "24h" }
);
const newCookie = { token: newToken, userId: user.id };
const cryptedToken = cryptojs.AES.encrypt(JSON.stringify(newCookie), process.env.COOKIE_KEY).toString();
res.cookie('snToken', cryptedToken, {
httpOnly: true,
maxAge: 86400000
});
//res.status(200).send({ message: 'The user is successfully connected!', data: user });
res.status(200).send({ message: 'The user is successfully connected!', data: user, cryptedToken: cryptedToken });
}
});
} catch (error) {
res.send({ error: 'An error has occured while trying to log in!' });
}
}
The call of these middlwares in my app.js:
app.get('*', checkUser);
In your current code, you get a Hex encoded ASCII string after decryption
7b22746f6b656e223a2265794a68624763694f694a49557a49314e694973496e523563434936496b705856434a392e65794a3163325679535751694f6a45314c434a70595851694f6a45324e4445314e6a45324d545173496d5634634349364d5459304d5459304f4441784e48302e693670564f486443473456445154362d3749644545536f326251467765394d4b34554a316f363676564334222c22757365724964223a31357d,
which contains your cookie as a stringified JSON.
Instead of toString() after decrypting, which causes the hex encoded output, call toString(cryptojs.enc.Utf8) to get a JSON String and then parse it to an object:
const bytes = cryptojs.AES.decrypt(cryptedToken, process.env.COOKIE_KEY);
const cookie = JSON.parse(bytes.toString(cryptojs.enc.Utf8));
console.log("token", cookie.token);
the result is a correct JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjE1LCJpYXQiOjE2NDE1NjE2MTQsImV4cCI6MTY0MTY0ODAxNH0.i6pVOHdCG4VDQT6-7IdEESo2bQFwe9MK4UJ1o66vVC4
Related
I am trying to implement the usage of JWT but it seems that my token is not being stored.
this is the creating of the token...
router.post('/index', async (req, res) => {
let post = { //retreive user input
username: req.body.username,
password: req.body.password,
}
try {
const user = await dbb('users').first('*').where({username: post.username});
if(!user) {
res.render(path.resolve('./myviews/index'), { //display if user is not found
info: 'The Username Or Password You Have Entered Does Not Match Our Records'
});
}
if(user) {
const validPass = await bcrypt.compare(post.password, user.password);
if(validPass){
const token = jwt.sign(`${user}`, process.env.ACCESS_TOKEN);
res.json({token: token});
res.redirect('/home');
} else {
res.render(path.resolve('./myviews/index'), { //display if user is not found
info: 'The Username Or Password You Have Entered Does Not Match Our Records'
});
}
}
} catch(e) {
console.log(e);
}
});
this is the function that is supposed to use the token...
function authToken(req, res, next) {
const authHeader = req.headers['authorization'];
if(typeof authHeader !== 'undefined') {
console.log("here")
const bearer = authHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
} else {
res.sendStatus(401);
}
im wondering if anyone can help me understand where i am going wrong
I have created a model and the name of the table is users. In the Model, i have a method generateToken which is used to generate the web token.
I have used sequelized ORM.
module.exports = (sequelize, Sequelize) => {
const Tutorial = sequelize.define("users", {
age: {
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
});
Tutorial.generateToken = async function () {
try {
const token = jwt.sign({ _id: this.id }, "ThisIsTaskApp")
console.log(token)
}
catch (error) {
response.send('there is an error' + error)
console.log('there is an error' + error)
}
}
return Tutorial;
};
I want to create a web token when my email id and password matches, so for that i have used the generateToken but i am getting an error
TypeError: user.generateToken is not a function
I believe i have error with javascript importing the generateToken function.
const jwt = require('jsonwebtoken')
const user = db.users;
const generateToken = require('./models/users')
app.post('/login', async (req, res) => {
try {
var email = req.body.email;
var password = req.body.password;
await user.findOne({ where: { email: email, password: password } })
.then(user => {
if (user === null) {
res.status(404).json({
message: 'Auth Failed'
})
}
else {
const token = user.generateToken()
res.status(200).json(user)
}
})
}
catch (error) {
console.log(error)
return res.json({ 'status': 400 })
}
})
Please help me fix this issue and generating web token.
Try using
generateToken.generateToken()
there instead of
user.generateToken()
Because you are basically exporting the model of users in generate token variable, so that function is accessible from that variable not from user variable.
There is some issue with your code related to async, please try this one
const user = db.users;
app.post("/login", async (req, res) => {
try {
var email = req.body.email;
var password = req.body.password;
const userdata = await user.findOne({ where: { email: email, password: password } });
if (userdata === null) {
return res.status(404).json({
message: "Auth Failed",
});
}
const token = await userdata.generateToken();
console.log("🚀 ~ token", token)
return res.status(200).json(userdata);
} catch (error) {
console.log(error);
return res.json({ status: 400 });
}
});
I think you need to require jsonwebtoken in /models/users as well as in the route handler file
I was following a tutorial at Authentication in NodeJS With Express and Mongo - CodeLab #1
I got everything to work perfectly, but the tutorial does not address how to log out a user.
From what I can tell, the session is being saved on Mongoose Atlas, which is the database I am using. When I log a user in with Postman, I get a token back. But I am not sure how to configure the /logout route.
Here is my code:
//routes/user.js
const express = require("express");
const { check, validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const router = express.Router();
const auth = require("../middleware/auth");
const User = require("../models/User");
/**
* #method - POST
* #param - /signup
* #description - User SignUp
*/
//Signup
router.post(
"/signup",
[
check("username", "Please Enter a Valid Username")
.not()
.isEmpty(),
check("email", "Please enter a valid email").isEmail(),
check("password", "Please enter a valid password").isLength({
min: 6
})
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
const {
username,
email,
password
} = req.body;
try {
let user = await User.findOne({
email
});
if (user) {
return res.status(400).json({
msg: "User Already Exists"
});
}
user = new User({
username,
email,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
"randomString", {
expiresIn: 10000
},
(err, token) => {
if (err) throw err;
res.status(200).json({
token
});
}
);
} catch (err) {
console.log(err.message);
res.status(500).send("Error in Saving");
}
}
);
// Login
router.post(
"/login",
[
check("email", "Please enter a valid email").isEmail(),
check("password", "Please enter a valid password").isLength({
min: 6
})
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
const { email, password } = req.body;
try {
let user = await User.findOne({
email
});
if (!user)
return res.status(400).json({
message: "User Not Exist"
});
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch)
return res.status(400).json({
message: "Incorrect Password !"
});
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
"randomString",
{
expiresIn: 3600
},
(err, token) => {
if (err) throw err;
res.status(200).json({
token
});
}
);
} catch (e) {
console.error(e);
res.status(500).json({
message: "Server Error"
});
}
}
);
// router.route("/logout").get(function (req, res, next) {
// if (expire(req.headers)) {
// delete req.user;
// return res.status(200).json({
// "message": "User has been successfully logged out"
// });
// } else {
// return next(new UnauthorizedAccessError("401"));
// }
// });
router.get("/me", auth, async (req, res) => {
try {
// request.user is getting fetched from Middleware after token authentication
const user = await User.findById(req.user.id);
res.json(user);
} catch (e) {
res.send({ message: "Error in Fetching user" });
}
});
router.get('/logout', isAuthenticated, function (req, res) {
console.log('User Id', req.user._id);
User.findByIdAndRemove(req.user._id, function (err) {
if (err) res.send(err);
res.json({ message: 'User Deleted!' });
})
});
module.exports = router;
function isAuthenticated(req, res, next) {
console.log("req: " + JSON.stringify(req.headers.authorization));
// if (!(req.headers && req.headers.authorization)) {
// return res.status(400).send({ message: 'You did not provide a JSON web token in the authorization header' });
//}
};
///middleware/auth.js
const jwt = require("jsonwebtoken");
module.exports = function (req, res, next) {
const token = req.header("token");
if (!token) return res.status(401).json({ message: "Auth Error" });
try {
const decoded = jwt.verify(token, "randomString");
req.user = decoded.user;
next();
} catch (e) {
console.error(e);
res.status(500).send({ message: "Invalid Token" });
}
};
///models/User.js
const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now()
}
});
// export model user with UserSchema
module.exports = mongoose.model("user", UserSchema);
So my question is, how can I implement a /logout route so that if the user clicks the logout button and invokes that route, their token is destroyed. I am only asking about the back-end part. I can handle using axios.
Thanks.
From what I see, you are not saving any session data or storing tokens anywhere - which is great. You are simply appending the token to your headers in requests to the API.
So the only thing you can do is possibly expire the token in the /logout route
and then ensure you delete the token on the client - could be localStorage, sessionStorage etc - your client code needs to kill the token so it cannot be included again.
Side note:
You are not extending the token lifetime anywhere, so even if the user keeps interacting on the website, the token expiration is not being updated. You will need to manually refresh the token/generate a new token to have a sliding expiration.
I would suggest you save the token in cookies rather. Set the cookie to HttpOnly, Secure, and specify the domain. This is far more secure and will allow you to also expire the cookie from the API. If any scripts you include get compromised, they can access all your users’ tokens easily.
Example:
import {serialize} from 'cookie';
import jsend from 'jsend';
...
const token = jwt.sign(
{
id: validationResult.value.id // whatever you want to add to the token, here it is the id of a user
},
privateKeyBuffer,
{
expiresIn: process.env.token_ttl,
algorithm: 'RS256'
});
const cookieOptions = {
httpOnly: true,
path: '/',
maxAge: process.env.token_ttl,
expires: new Date(Date.now() + process.env.token_ttl),
sameSite: process.env.cookie_samesite, // strict
domain: process.env.cookie_domain, // your domain
secure: process.env.cookie_secure // true
};
const tokenCookie = await serialize('token', token, cookieOptions);
res.setHeader('Set-Cookie', [tokenCookie]);
res.setHeader('Content-Type', 'application/json');
res.status(200).json(jsend.success(true));
Then in logout:
// grab from req.cookies.token and validate
const token = await extractToken(req);
// you can take action if it's invalid, but not really important
if(!token) {
...
}
// this is how we expire it - the options here must match the options you created with!
const cookieOptions = {
httpOnly: true,
path: '/',
maxAge: 0,
expires: 0,
sameSite: process.env.cookie_samesite, // strict
domain: process.env.cookie_domain, // your domain
secure: process.env.cookie_secure // true
};
// set to empty
const tokenCookie = await serialize('token', '', cookieOptions);
res.setHeader('Set-Cookie', [tokenCookie]);
res.setHeader('Content-Type', 'application/json');
res.status(200).json(jsend.success(true));
As you have used JWT the backend will always check 2 things
1. Proper token
2. If time is over for that particular (You should handle this one)
For 2nd point, if the user time is up than from frontend you may delete the token if you have stored the token in localstorage.
For logout when user clicks on logout just delete jwt from localstorage and redirect to login or other page
I'm following a tutorial: https://github.com/eXtremeXR/APIAuthenticationWithNode/tree/Part_%2312
And during the sign-up local part, there was an error
Unhandled promise rejections are deprecated.
But I managed to solved that by using try-catch blocks. But again due to the main error:
TypeError: Cannot read property 'alg' of undefined
Every request I make returns me an error even though the registration is really successful.
The error points me to this block:
signToken = user => {
return JWT.sign({
iss: 'CodeWorkr',
sub: user.id,
iat: new Date().getTime(), // current time
exp: new Date().setDate(new Date().getDate() + 1) // current time + 1 day ahead
}, JWT_SECRET);
}
What's the cause of this and how do I solve it?
Here's the full controller code:
const JWT = require('jws');
const User = require('../models/user');
const { JWT_SECRET } = require('../configuration');
signToken = user => {
return JWT.sign({
iss: 'CodeWorkr',
sub: user.id,
iat: new Date().getTime(), // current time
exp: new Date().setDate(new Date().getDate() + 1) // current time + 1 day ahead
}, JWT_SECRET);
}
module.exports = {
signUp: async (req, res, next) => {
try {
const { email, password } = req.body;
// Check if there is a user with the same email
const foundUser = await User.findOne({ "local.email": email });
if (foundUser) {
return res.status(403).json({ error: 'Email is already in use'});
}
// Create a new user
const newUser = new User({
method: 'local',
local: {
email: email,
password: password
}
});
await newUser.save();
// Generate the token
const token = signToken(newUser);
// Respond with token
res.status(200).json({ token });
} catch (err) {
res.status(500).send({
message: "Error" + err
})
}
},
signIn: async (req, res, next) => {
// Generate token
const token = signToken(req.user);
res.status(200).json({ token });
},
googleOAuth: async (req, res, next) => {
// Generate token
const token = signToken(req.user);
res.status(200).json({ token });
},
facebookOAuth: async (req, res, next) => {
// Generate token
const token = signToken(req.user);
res.status(200).json({ token });
},
secret: async (req, res, next) => {
console.log('I managed to get here!');
res.json({ secret: "resource" });
}
}
First off, I got the answer. I'm wondering how is it my tags in this question draw much fewer SO users. It seems to me that you can get answers faster when you're in the mobile development tags.
The answer is the project is somehow requiring wrong library? In the sample project, it has:
const JWT = require('jws');
But after looking at some more JWT sample projects, I realized it should be:
const jwt = require('jsonwebtoken');
solved!
I am trying to complete jwt sign in I am trying to create the jwt token in login.Then I am trying to use it within my user-questions route.
I am using a react front end.
Is this the correct way to do so?
I am currently getting error
const token = req.cookies.auth;
[0] ^
[0]
[0] ReferenceError: req is not defined
Below is my routes login code which assigns the token once the my sql server return that the values for email and password exist. User-questions tries to use this jwt. and I have also included how the token is verfied in a function
Verfiy users
app.get("/user-questions", verifyToken, function(req, res) {
app.use(function(req, res, next) {
// decode token
if (token) {
jwt.verify(token, "secret", function(err, token_data) {
if (err) {
console.info("token did not work");
return res.status(403).send("Error");
} else {
req.user_data = token_data;
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.execute("dbo.ViewQuestions", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
next();
});
});
}
});
} else {
console.info("no token");
console.log("no token");
return res.status(403).send("No token");
}
});
});
Login route
app.post("/login", async (req, response) => {
try {
await sql.connect(config);
var request = new sql.Request();
var Email = req.body.email;
var Password = req.body.password;
console.log({ Email, Password });
request.input("Email", sql.VarChar, Email);
request.input("Password", sql.VarChar, Password);
var queryString =
"SELECT * FROM TestLogin WHERE email = #Email AND password = #Password";
//"SELECT * FROM RegisteredUsers WHERE email = #Email AND Password = HASHBYTES('SHA2_512', #Password + 'skrrt')";
const result = await request.query(queryString);
if (result.recordsets[0].length > 0) {
console.info("/login: login successful..");
console.log(req.body);
token = jwt.sign(
{ Email },
"secretkey",
{ expiresIn: "30s" },
(err, token) => {
res.json({
token
});
res.cookie("auth", token);
res.send("ok");
}
);
} else {
console.info("/login: bad creds");
response.status(400).send("Incorrect email and/or Password!");
}
} catch (err) {
console.log("Err: ", err);
response.status(500).send("Check api console.log for the error");
}
});
Verify users
// Verify Token
function verifyToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers["authorization"];
// Check if bearer is undefined
if (typeof bearerHeader !== "undefined") {
// Split at the space
const bearer = bearerHeader.split(" ");
// Get token from array
const bearerToken = bearer[1];
// Set the token
req.token = bearerToken;
// Next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}
Please advise if this in theory should work. And if not please advise how to resolve.
EDIT :
The error has been resolved however now simply my jwt tokens to do not work. As when logged in and I manually route to user-questions it does not load the component and within the console it says 403 not available (this is set in the code when the jwt token is not working).
UPDATE:
How would I include
['authorization'] = 'Bearer ' + token;
into
handleSubmit(e) {
e.preventDefault();
if (this.state.email.length < 8 || this.state.password.length < 8) {
alert(`please enter the form correctly `);
} else {
const data = { email: this.state.email, password: this.state.password };
fetch("/login", {
method: "POST", // or 'PUT'
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
// .then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
}
}
There are a couple of errors with your code:
In your /login route:
You are trying to set the "auth" cookie after the response is being sent
You are trying to send a response twice, once via res.json and once via res.send
You are assigning to a token variable that no longer exists (token = jwt.sign(...))
In your verifyToken method:
This method is only verifying that the request has a token set, it's not validating or decoding it. I would consider moving your jwt.verify() call to this method.
In your /user-questions route:
You're calling app.use inside of app.get, when both of these are intended to be called at the root level. Remove your app.use call.
You need to grab token from the request, ex. const { token } = req;
You are sending a response via res.json(), but you are still calling next() afterwards. From the Express docs:
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.
This is how I would make these changes:
/login route:
app.post("/login", async (req, response) => {
try {
await sql.connect(config);
var request = new sql.Request();
var Email = req.body.email;
var Password = req.body.password;
console.log({ Email, Password });
request.input("Email", sql.VarChar, Email);
request.input("Password", sql.VarChar, Password);
var queryString =
"SELECT * FROM TestLogin WHERE email = #Email AND password = #Password";
//"SELECT * FROM RegisteredUsers WHERE email = #Email AND Password = HASHBYTES('SHA2_512', #Password + 'skrrt')";
const result = await request.query(queryString);
if (result.recordsets[0].length > 0) {
console.info("/login: login successful..");
console.log(req.body);
jwt.sign(
{ Email },
"secretkey",
{ expiresIn: "30s" },
(err, token) => res.cookie('auth', token).json({ token })
);
} else {
console.info("/login: bad creds");
response.status(400).send("Incorrect email and/or Password!");
}
} catch (err) {
console.log("Err: ", err);
response.status(500).send("Check api console.log for the error");
}
});
verifyToken method:
// Verify Token
function verifyToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers["authorization"];
// Check if bearer is undefined
if (typeof bearerHeader !== "undefined") {
// Split at the space
const bearer = bearerHeader.split(" ");
// Get token from array
const bearerToken = bearer[1];
// verify the token and store it
jwt.verify(bearerToken, "secret", function(err, decodedToken) {
if (err) {
console.info("token did not work");
return res.status(403).send("Error");
}
// Set the token
req.token = bearerToken;
req.decodedToken = decodedToken;
next();
});
} else {
// Forbidden
res.sendStatus(403);
}
}
/user-questions route:
app.get("/user-questions", verifyToken, function(req, res) {
// if a request has made it to this point, then we know they have a valid token
// and that token is available through either req.token (encoded)
// or req.decodedToken
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.execute("dbo.ViewQuestions", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});