繁体   English   中英

如何在graphql node.js中使用jwt

[英]how to use jwt with graphql nodejs

你好,graphql的新手,我想创建一个注册页面,当用户在mysql数据库中的用户表中注册其ID和角色时,将使用jwt对其进行加密,但是当我尝试使用它时,它没有返回任何东西,它用graphiQL返回了这个

{
  "data": {
    "registerUser": null
  }
}

import models from '../../../models/index.js';
import User from '../../types/user.js';
import UserInput from '../../inputs/user.js';
const jsonwebtoken = require('jsonwebtoken')
require('dotenv').config()

export default {
    type: User,
    args: {
        user: {
            type: UserInput
        }
    },
    resolve (_,args) {
        models.user.create({ 
            name: args.user.name,
            email: args.user.email,
            password: args.user.password,
            role:"Student"
        }).then(function(newUser) {
            return jsonwebtoken.sign(
                { id: newUser.id, role: newUser.role },
                process.env.JWT_SECRET,
                { expiresIn: '1y' }
              )
        });
    }
};

请问我该如何解决这个问题,以便它将返回jwt令牌

我认为您只错过了models.user.create之前的return语句:

resolve (_,args) {
  return models.user.create({ 
    name: args.user.name,
    email: args.user.email,
    password: args.user.password,
    role:"Student"
  }).then(function(newUser) {
    return jsonwebtoken.sign(
      { id: newUser.id, role: newUser.role },
      process.env.JWT_SECRET,
      { expiresIn: '1y' }
    )
  });
}

似乎您对使用JWT和GraphQL进行身份验证感兴趣。 我认为最好使用上下文并将JWT设置为cookie。 如果您有兴趣,我写了一篇简短的文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM