Local authentication — verifying users by email and password rather than delegating to a provider such as Google — remains the most common approach for modern sites, and it is also where most GraphQL newcomers get stuck. The hard parts are not the resolver code itself but the surrounding choices: an ORM that is simple to bootstrap, secure token generation, password hashing, and the HTTP layer underneath the GraphQL server.
The build described here relies on Apollo Server 2, JSON Web Tokens (JWT) and the Sequelize ORM on Node.
Authentication versus authorization
The two terms are routinely conflated, but they cover different jobs:
- Authentication identifies or verifies a user.
- Authorization validates which routes, or which parts of the app, an already authenticated user may access.
A login system built along these lines follows a fixed sequence:
- The user registers with an email and a password.
- The supplied credentials are written to the database.
- Once registration finishes, the user is sent to the login screen.
- After authenticating, the user is granted access to specific resources.
- The user's state is kept in a browser storage medium —
localStorage, cookies or a session — or in a JWT.
Prerequisites
To follow along you need:
- Node 6 or higher and Yarn (recommended) or NPM
- GraphQL Playground
- A working knowledge of GraphQL and Node
The dependency list
- Apollo Server — an open-source GraphQL server compatible with any GraphQL client. No Express here; Apollo Server itself exposes the GraphQL API.
- bcryptjs — hashes user passwords before they reach the database. It draws secure random numbers through the Web Crypto API's
getRandomValuesinterface. - dotenv — loads environment variables in from a
.envfile. - jsonwebtoken — generates the JWT. After login, every subsequent request carries that token, which is what unlocks the routes and resources permitted to it.
- nodemon — watches the directory and restarts the Node application on changes, so there is no need to stop and start the server by hand after every edit.
- mysql2 — an SQL client for Node, needed to connect to the SQL server and run migrations.
- sequelize — a promise-based Node ORM covering Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It generates migrations and models automatically.
- sequelize-cli — runs the Sequelize commands. Install it globally with
yarn add --global sequelize-cli.
Scaffolding the project
Start by creating a new folder for the project and initialising it inside:
yarn init -y
The -y flag accepts the defaults for every yarn init question. Add a package.json and install the project dependencies:
yarn add apollo-server bcrpytjs dotenv jsonwebtoken nodemon sequelize sqlite3
Babel goes in next as part of the development environment:
yarn add babel-cli babel-preset-env babel-preset-stage-0 --dev
Run touch .babelrc to create and open the Babel config file, then add the following:
{
"presets": ["env", "stage-0"]
}
It is convenient to have the server start up and migrate data in one step; the package.json scripts can automate that:
"scripts": {
"migrate": " sequelize db:migrate",
"dev": "nodemon src/server --exec babel-node -e js",
"start": "node src/server",
"test": "echo \"Error: no test specified\" && exit 1"
},
Here is the complete package.json at this point:
{
"name": "graphql-auth",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"migrate": " sequelize db:migrate",
"dev": "nodemon src/server --exec babel-node -e js",
"start": "node src/server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"apollo-server": "^2.17.0",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.4",
"sequelize": "^6.3.5",
"sqlite3": "^5.0.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1"
}
}
Sequelize is the ORM for this project, with MySQL underneath it. Running sequelize init (with Sequelize installed globally beforehand) generates /config, /models and /migrations. The database itself needs a table called graphql_auth; the source uses Laragon and phpMyAdmin for local serving and table management, but any equivalent works.
Wiring the database and models
Database credentials live in a .env file at the project root, which is populated once the table exists:
NODE_ENV=development
DB_HOST=localhost
DB_USERNAME=
DB_PASSWORD=
DB_NAME=
Inside /config, rename config.json to config.js so the credentials can be read from the environment:
require('dotenv').config()
const dbDetails = {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: 'mysql'
}
module.exports = {
development: dbDetails,
production: dbDetails
}
process.env is a global Node injects to represent the current state of the system environment. With the real values in place, uncomment and fill in the entries:
NODE_ENV=development
DB_HOST=localhost
DB_USERNAME=graphql_auth
DB_PASSWORD=
DB_NAME=<your_db_username_here>
Next, a .sequelizerc file at the project root points Sequelize at the right paths:
const path = require('path')
module.exports = {
config: path.resolve('config', 'config.js')
}
Then have /models/index.js consume that configuration by editing its config variable:
const config = require(__dirname + '/../../config/config.js')[env]
The only model needed is User, which Sequelize can scaffold automatically:
sequelize model:generate --name User --attributes username:string,email:string,password:string
Edit the generated user.js in /models to declare the username, email and password attributes:
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.STRING,
}
}, {});
return User;
};
Run a migration so schema changes stay tracked:
yarn migrate
Schema, resolvers and server
In the src folder, create /schema/schema.js:
const { gql } = require('apollo-server')
const typeDefs = gql`
type User {
id: Int!
username: String
email: String!
}
type AuthPayload {
token: String!
user: User!
}
type Query {
user(id: Int!): User
allUsers: [User!]!
me: User
}
type Mutation {
registerUser(username: String, email: String!, password: String!): AuthPayload!
login (email: String!, password: String!): AuthPayload!
}
`
module.exports = typeDefs
Apollo Server requires the schema to be wrapped with gql, imported from graphql-tag.
The resolver file goes in /resolvers/resolver.js:
const bcrypt = require('bcryptjs')
const jsonwebtoken = require('jsonwebtoken')
const models = require('../models')
require('dotenv').config()
const resolvers = {
Query: {
async me(_, args, { user }) {
if(!user) throw new Error('You are not authenticated')
return await models.User.findByPk(user.id)
},
async user(root, { id }, { user }) {
try {
if(!user) throw new Error('You are not authenticated!')
return models.User.findByPk(id)
} catch (error) {
throw new Error(error.message)
}
},
async allUsers(root, args, { user }) {
try {
if (!user) throw new Error('You are not authenticated!')
return models.User.findAll()
} catch (error) {
throw new Error(error.message)
}
}
},
Mutation: {
async registerUser(root, { username, email, password }) {
try {
const user = await models.User.create({
username,
email,
password: await bcrypt.hash(password, 10)
})
const token = jsonwebtoken.sign(
{ id: user.id, email: user.email},
process.env.JWT_SECRET,
{ expiresIn: '1y' }
)
return {
token, id: user.id, username: user.username, email: user.email, message: "Authentication succesfull"
}
} catch (error) {
throw new Error(error.message)
}
},
async login(_, { email, password }) {
try {
const user = await models.User.findOne({ where: { email }})
if (!user) {
throw new Error('No user with that email')
}
const isValid = await bcrypt.compare(password, user.password)
if (!isValid) {
throw new Error('Incorrect password')
}
// return jwt
const token = jsonwebtoken.sign(
{ id: user.id, email: user.email},
process.env.JWT_SECRET,
{ expiresIn: '1d'}
)
return {
token, user
}
} catch (error) {
throw new Error(error.message)
}
}
},
}
module.exports = resolvers
This file imports the models, bcrypt and jsonwebtoken, then initializes the environment variables. The query resolver exposes three functions: me, user and allUsers.
mereturns the details of the currentlyloggedInuser, reading auserobject from the context argument. The context provides database access, used to load the user by the ID given as a query argument.userreturns a user's details based on theirid, takingidas the context argument alongside theuserobject.allUsersreturns every user's details.
The user object is populated when the state is loggedIn and is null otherwise; it gets created in the mutations.
The mutation resolver has two functions, registerUser and loginUser. registerUser takes the username, email and password, writes a new row to the database, hashes the password with bcrypt.hash(password, 10) from bcryptjs, and signs the id and email into a JWT with jsonwebtoken.sign, which signs synchronously. On success it returns the JWT string and user profile; on failure, an error message.
login takes email and password and verifies them against stored values. It first checks whether the email exists anywhere in the user database:
models.User.findOne({ where: { email }})
if (!user) {
throw new Error('No user with that email')
}
The password match is then checked with bcrypt's bcrypt.compare:
const isValid = await bcrypt.compare(password, user.password)
if (!isValid) {
throw new Error('Incorrect password')
}
As in registerUser, jsonwebtoken.sign then generates a JWT string, and the login mutation returns the token and user object. The JWT_SECRET that signing depends on goes into .env:
JWT_SECRET=somereallylongsecret
The entry point is server.js at the project root:
const { ApolloServer } = require('apollo-server')
const jwt = require('jsonwebtoken')
const typeDefs = require('./schema/schema')
const resolvers = require('./resolvers/resolvers')
require('dotenv').config()
const { JWT_SECRET, PORT } = process.env
const getUser = token => {
try {
if (token) {
return jwt.verify(token, JWT_SECRET)
}
return null
} catch (error) {
return null
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const token = req.get('Authorization') || ''
return { user: getUser(token.replace('Bearer', ''))}
},
introspection: true,
playground: true
})
server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
It imports the schema, resolvers and jwt, and initializes the environment variables. Token verification runs through verify; jwt.verify accepts the token and the JWT secret as parameters. The server is an ApolloServer instance taking typeDefs and resolvers. Start it with yarn dev.
Exercising the API in GraphQL Playground
Registering, logging in, and viewing all users or one user by ID are all testable in GraphQL Playground, reachable through the Playground app or by opening localhost://4000 in a browser. The register mutation:
mutation {
registerUser(username: "Wizzy", email: "[email protected]", password: "wizzyekpot" ){
token
}
}
returns roughly the following:
{
"data": {
"registerUser": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImVtYWlsIjoiZWtwb3RAZ21haWwuY29tIiwiaWF0IjoxNTk5MjQwMzAwLCJleHAiOjE2MzA3OTc5MDB9.gmeynGR9Zwng8cIJR75Qrob9bovnRQT242n6vfBt5PY"
}
}
}
The login mutation uses the details just created:
mutation {
login(email:"[email protected]" password:"wizzyekpot"){
token
}
}
with a response like:
{
"data": {
"login": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImVtYWlsIjoiZWtwb3RAZ21haWwuY29tIiwiaWF0IjoxNTk5MjQwMzcwLCJleHAiOjE1OTkzMjY3NzB9.PDiBKyq58nWxlgTOQYzbtKJ-HkzxemVppLA5nBdm4nc"
}
}
}
Querying a single user requires passing the user token as an authorization header, set on the HTTP Headers tab:

Paste this header value:
{
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImVtYWlsIjoiZWtwb3RAZ21haWwuY29tIiwiaWF0IjoxNTk5MjQwMzcwLCJleHAiOjE1OTkzMjY3NzB9.PDiBKyq58nWxlgTOQYzbtKJ-HkzxemVppLA5nBdm4nc"
}
The query itself:
query myself{
me {
id
email
username
}
}
returns something along these lines:
{
"data": {
"me": {
"id": 15,
"email": "[email protected]",
"username": "Wizzy"
}
}
}
Fetching a user by ID instead:
query singleUser{
user(id:15){
id
email
username
}
}
And fetching all users:
{
allUsers{
id
username
email
}
}
Takeaways
GraphQL allowed the entire authentication API to run through a single endpoint. Sequelize handled the SQL-side relationships, so the models took almost no attention, and no HTTP server library such as Express was needed — Apollo GraphQL served as the middleware instead. Apollo Server 2 makes library-independent GraphQL servers possible. The tutorial's source code is on GitHub.



