Add an Authentication Feature in GraphQL
Learn how to add authentication features to the GraphQL application.
We'll cover the following...
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 typescalar Timetype Blog {id: ID!title: String!content: String!author: UsercreatedAt: Time!updatedAt: Time}# User represents user datatype 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 userinput NewUser {username: String!email: String!password: String!}# LoginInput represents data input for logininput 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 userregister(input: NewUser!): String!# login to authenticate the userlogin(input: LoginInput!): String!newBlog(input: NewBlog!): Blog!editBlog(input: EditBlog!): Blog!deleteBlog(input: DeleteBlog!): Boolean!}
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 containsid,username,email, andpassword. -
input NewUser: TheNewUseracts as data input for registration defined in lines 29-33. -
input LoginInput: TheLoginInputacts as data input for login defined in lines 36-39. -
register(input: NewUser!): String!: Theregistermutation 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!: Theloginmutation 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 work properly with the Go application.
To add the ...