I',试图验证一个用户,我可以创建一个用户并获得承载,但之后我添加了这段代码来验证,它每隔几秒钟就会显示以下错误:
UnauthorizedError: invalid algorithm
at /mnt/c/Projects/myProject/node_modules/express-jwt/lib/index.js:105:22
at /mnt/c/Projects/myProject/node_modules/jsonwebtoken/verify.js:121:14
at getSecret (/mnt/c/Projects/myProject/node_modules/jsonwebtoken/verify.js:90:14)
at Object.module.exports [as verify] (/mnt/c/Projects/myProject/node_modules/jsonwebtoken/verify.js:94:10)
at verifyToken (/mnt/c/Projects/myProject/node_modules/express-jwt/lib/index.js:103:13)
at fn (/mnt/c/Projects/myProject/node_modules/async/lib/async.js:746:34)
at /mnt/c/Projects/myProject/node_modules/async/lib/async.js:1213:16
at /mnt/c/Projects/myProject/node_modules/async/lib/async.js:166:37
at /mnt/c/Projects/myProject/node_modules/async/lib/async.js:706:43
at /mnt/c/Projects/myProject/node_modules/async/lib/async.js:167:37
代码:
const express = require("express");
const { ApolloServer } = require("apollo-server-express");
const jwt = require("express-jwt");
const typeDefs = require("./settings/schema");
const resolvers = require("./settings/resolvers");
const JWT_SECRET = require("./settings/constants");
const app = express();
const auth = jwt({
secret: JWT_SECRET,
credentialsRequired: false,
algorithms: ['RS256'],
});
app.use(auth);
const server = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: "/graphql",
},
context: ({ req }) => {
const user = req.headers.user
? JSON.parse(req.headers.user)
: req.user
? req.user
: null;
return { user };
},
});
server.applyMiddleware({ app });
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log("The server started on port " + PORT);
});
不能弄清楚为什么'RS256'不是一个有效的算法,我应该需要其他东西吗?不同的任务需要不同的算法吗?
constants.js包含以下内容:
const JWT_SECRET = "sdlkfoish23@#$dfdsknj23SD";
module.exports = JWT_SECRET;
感谢编辑:
我不使用Auth0, OAuth或任何其他服务,我想在这里自己验证用户
当一个新用户通过GraphQL API添加到DB (postgres)时,我正在注册一个键:
mutation {
register(login: "john", password: "doe")
}
答案:
{
"data": {
"register": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NiwibG9naW4iOiJqb2VsIiwiaWF0IjoxNjE0NDM0NzMwLCJleHAiOjE2MTQ0MzQ5MTB9.ALltmClvlzxDJJ2FgZcFzstDUP5CY1xRzs8yQwheEn8"
}
}
那么我就像这样使用这个承载符:
// Headers
{
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NiwibG9naW4iOiJqb2VsIiwiaWF0IjoxNjE0NDM0NzMwLCJleHAiOjE2MTQ0MzQ5MTB9.ALltmClvlzxDJJ2FgZcFzstDUP5CY1xRzs8yQwheEn8"
}
// Query
query {
current {
id,
login
}
}
我收到这个答案(也不知道为什么):
{
"error": "Unexpected token < in JSON at position 0"
}
和这篇文章顶部的错误在终端
对于具有JWT_SECRET
的承载令牌,使用HS256
算法。RSA256
算法需要公钥和私钥对。
const auth = jwt({
secret: JWT_SECRET,
credentialsRequired: false,
algorithms: ['HS256']
});