3 回答
TA贡献1856条经验 获得超5个赞
您可以在上下文回调时检查 jwt 令牌
server = new ApolloServer({
schema: schema ,
graphiql: true ,
context:({req, connection} )=>
if connection
token = connection.context["x-access-token"]
decoded = await LoginService.verify token #verify by jwt
if decoded == null
throw new Error("auth required")
return connection.context
headers = req.headers
token = headers["x-access-token"]
decoded = await LoginService.verify token #verify by jwt
return authed: decoded != null
})
TA贡献2051条经验 获得超10个赞
我只是这样做解决它:
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req, connection }) => {
if (connection) {
// check connection for metadata
return connection.context;
} else {
// check from req
const token = req.headers.authorization
if(token !== "null"){
try{
//validate user in client.
const currentUser = await jwt.verify(token, process.env.SECRET);
//add user to request
req.currentUser = currentUser;
return {
currentUser
}
}catch(err){
return "";
}
}
}
},
});
添加回答
举报