...

/

Authorization and the logOut Resolver

Authorization and the logOut Resolver

Learn how to implement authorization in GraphQL resolvers.

So far, we’ve implemented setting a cookie in the login resolver and have configured Apollo Studio to send it back on every request. However, we don’t do anything with this cookie when we receive it back.

Now, we’ll see how to read a user ID from a cookie and use it in resolvers for authorization. We will also see how we can implement the logOut mutation.

Reading incoming cookies

Let’s see how we can check an incoming JWT token and extract a user ID from it if it’s valid. If we get a valid user ID from a request, we pass it to the resolvers that handle user IDs using the GraphQL context.

As a reminder, we’re currently creating a context with Express request and response objects.

Press + to interact
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({req, res}) => {
return {
req,
res
}
}
})

To read our cookies, we should use the req.cookies field that contains all cookies sent in a request. We can get our cookie from it, which has been named authCookie.

Press + to interact
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('./auth.js')
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({req, res}) => {
const authCookie = req.cookies.authCookie
logger.info(`Auth cookie: ${req.cookies.authCookie}`)
return {
req,
res
}
}
})

If we print the value of this cookie, we’ll see that it contains a ...