I have this createUser method:
const createUser = (request, response) => {
const { username, password, score } = request.body
database("user")
.select()
.where({ username })
.first()
.then(user => {
if (!user) {
return bcrypt.hash(password, 12)
.then(hashedPassword => {
return database("user").insert({
username, password_digest: hashedPassword, score
}).returning("*")
})
.then(users => {
const secret = "HERESYOURTOKEN"
jwt.sign(users[0], secret, (error, token) => {
console.log(users[0])
response.json({ token, user: users[0] })
})
})
}
response.send("Please choose another username")
}).catch(error => {
response.status(401).json({
error: error.message
})
})
}
And this Authentication method:
function authenticate(request, response, next){
const token = request.headers.authorization.split(" ")[1]
const secret = "HERESYOURTOKEN";
if (!token) {
response.sendStatus(401)
}
let id = null
try {
id = jwt.verify(token, secret)
} catch(error){
response.sendStatus(403)
}
const user = database("user")
.select()
.where("id", id)
.first()
request.user = user;
next();
}
And when I use the Postman to create a new user it gives me 401 Unauthorized error with message: enter image description here
The score data type is integer:
exports.up = function(knex) {
return knex.schema.createTable("user", table => {
table.increments()
table.string("username")
table.string("password_digest")
table.integer("score")
})
};
exports.down = function(knex) {
return knex.schema.dropTableIfExists("user")
};
Probably someone can help me with it.
The error should be from jwt.sign()
where your secret is not in a right format.
Can you try a simple const secret = "ABC"
to see if it works?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.