...

/

Add an Authentication Feature in GraphQL

Add an Authentication Feature in GraphQL

Learn how to add authentication features to the GraphQL application.

Generate a model from the new schema

Before creating basic authentication functionalities, the schema is modified. We add the schema for users and functionalities.

# represents the time data type
scalar Time
type Blog {
id: ID!
title: String!
content: String!
author: User
createdAt: Time!
updatedAt: Time
}
# User represents user data
type User {
id: ID!
username: String!
email: String!
password: String!
createdAt: Time!
updatedAt: Time
}
type Query {
blogs: [Blog!]!
blog(id: ID!): Blog!
}
# NewUser represents data input for creating a new user
input NewUser {
username: String!
email: String!
password: String!
}
# LoginInput represents data input for login
input LoginInput {
email: String!
password: String!
}
input NewBlog {
title: String!
content: String!
}
input EditBlog {
blogId: ID!
title: String!
content: String!
}
input DeleteBlog {
blogId: ID!
}
type Mutation {
# register to create a new user
register(input: NewUser!): String!
# login to authenticate the user
login(input: LoginInput!): String!
newBlog(input: NewBlog!): Blog!
editBlog(input: EditBlog!): Blog!
deleteBlog(input: DeleteBlog!): Boolean!
}
GraphQL schema

Based on the example above, the following schema is added:

  • type User: The schema for user data is defined in lines 14-21. The user data contains id, username, email, and password.

  • input NewUser: The NewUser acts as data input for registration defined in lines 29-33.

  • input LoginInput: The LoginInput acts as data input for login defined in lines 36-39.

  • register(input: NewUser!): String!: The register mutation used to perform a user registration is defined in line 58. The return value of this mutation is a string that will contain a JWT token.

  • login(input: LoginInput!): String!: The login mutation used to perform a login is defined in line 60. The return value of this mutation is a string that will contain a JWT token.

When using MongoDB, the additional tag called bson is required in the model. In this case, the model for user and blog data must contain bson because MongoDB uses binary JSON (BSON) to ...