简体   繁体   中英

how to use jwt with graphql nodejs

Hello am new to graphql i want to create a signup page that when ever a user signs up his id and role in the users table in mysql data base will be encrypted with jwt, but when i tried it, it didnt return any thing,it returned this with 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' }
              )
        });
    }
};

pls how can i solve this problem so that it will return the jwt token

I think you only missed a return statement before models.user.create :

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' }
    )
  });
}

It seems like you're interested in authentication with JWT and GraphQL. I think it's better to use the context and set the JWT to a cookie. I wrote a short article about this if you're interested.

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.

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