Search⌘ K
AI Features

Implementing the login Mutation

Understand how to implement a login mutation in a GraphQL API that validates user credentials, issues signed JWT tokens, and sets secure server-side cookies. Explore the process of hashing passwords with bcrypt to prevent timing attacks, signing JWTs to ensure token integrity, and configuring cookies for secure authentication sessions. Learn to test the mutation and configure Apollo Explorer to include cookies in requests for full authentication support.

So far, we’ve only done the prep work to implement authentication in our application. In this lesson, we’ll take the next step and implement the login mutation, which will receive users’ credentials, compare them to what we have in the database, and issue JWT tokens.

Since this will take some effort, we’ll focus on the login mutation in this lesson and leave the authorization and the logOut mutation for the next lesson.

Signing a JWT token

One question we haven’t talked about is, “Why is it safe to send a JWT token that contains information about any user?” After all, a JWT is self-contained and can include crucial data like user ID, user role, and permissions. So, why can’t someone change a JWT to impersonate another user or make oneself an admin?

To avoid this, we need to sign a JWT token using a cryptographic signature. A server should sign the JWT it creates and then check the signature on every incoming request to ensure that the token was issued by the server and wasn’t tampered with.

To sign a JWT token, we need to create a secret and use ...