【发布时间】:2019-05-27 08:12:32
【问题描述】:
我正在尝试使用 Apollo Server 2 为我的学校项目从头创建自己的后端服务器,并尝试创建用于授权和身份验证的安全功能,但不确定我是否应该这样做
我不太确定我是否为用户授权正确处理了错误,当出现错误时,服务器将使用堆栈跟踪响应错误,包括我的服务器文件夹目录。
我已经尝试了很多方法,到目前为止,使用 try catch 块可以最大程度地减少我得到的错误。
Auth.js /auth
import JWTR from 'jwt-redis'
import Redis from 'ioredis'
const redis = new Redis({
....
})
const jwtr = new JWTR(redis)
const token = req => req.headers.authorization.replace('Bearer', '').trim()
export const attemptSignIn = async (email, password) => {
var user = await User.findOne({ email })
if (!user || !await user.matchesPassword(password)) {
throw new AuthenticationError(INVALID_CREDENTIAL)
}
const payload = await jwtr.sign({ id: user.id }, JWT_SECRET)
user.token = payload
return user
}
export const decodeAuthToken = async req => {
if (!token(req)) {
throw new AuthenticationError(NO_JWT)
}
try {
const payload = await jwtr.verify(token(req), JWT_SECRET)
return payload
} catch (error) {
throw new AuthenticationError(INVALID_JWT)
}
}
export const checkAuthToken = async req => {
console.log(token(req))
if (!token(req)) {
throw new AuthenticationError(NO_JWT)
}
try {
const payload = await jwtr.verify(token(req), JWT_SECRET)
if (payload) {
return true
}
} catch (error) {
throw new AuthenticationError(INVALID_JWT)
}
return false
}
user.js /解析器
import * as Auth from '../auth'
users: async (root, args, { req }, info) => {
// Auth.checkSignedIn(req)
await Auth.checkAuthToken(req)
return User.find({})
},
我期待此错误消息,但没有在错误中获得此特定信息 - > /Users/firmanjamal/Desktop/School Project/FYP/backend/src/auth.js:68:11)
" at Proxy.checkAuthToken (/Users/firmanjamal/Desktop/School Project/FYP/backend/src/auth.js:68:11)",
" at process.internalTickCallback (internal/process/next_tick.js:77:7)"
"errors": [
{
"message": "The JWT you supply is not valid or already expired.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"user"
],
"extensions": {
"code": "UNAUTHENTICATED",
"exception": {
"stacktrace": [
"AuthenticationError: The JWT you supply is not valid or already expired.",
" at Proxy.checkAuthToken (/Users/firmanjamal/Desktop/School Project/FYP/backend/src/auth.js:68:11)",
" at process.internalTickCallback (internal/process/next_tick.js:77:7)"
]
}
}
}
],
【问题讨论】:
标签: javascript graphql apollo-server