Client-side Implementation
Login Mutation
This code defines a GraphQL mutation called Login
using the gql
tag from Apollo Client. It takes username
and password
as arguments and returns a token
and user details upon successful login.
const LOGIN_MUTATION = gql`
mutation Login($username: String!, $password: String!) {
login(username: $username, password: $password) {
token
user {
id
username
}
}
}
`;
const { data } = useMutation(LOGIN_MUTATION, {
variables: { username, password },
onCompleted: ({ login }) => {
localStorage.setItem('token', login.token);
// Redirect or perform other actions
}
});
Explanation: This code defines a GraphQL mutation using the gql
tag from Apollo Client, which represents a login operation. It takes username
and password
as arguments and returns a token
and user details upon successful login.
The useMutation
hook from Apollo Client is then used to execute the mutation. When the mutation completes successfully, the onCompleted
callback is called with the login
data, which contains the token. The token is then stored in the browser’s localStorage
for future use, such as for making authenticated requests to the server
Include JWT Token in Requests
This code creates an HTTP link using createHttpLink
from Apollo Client. The link is configured to send requests to the ‘/graphql’ endpoint on the same domain. It also includes an authorization
header with a JWT token retrieved from localStorage.getItem('token')
, or an empty string if the token is not found. This allows the client to send the JWT token along with each request to authenticate with the server
const httpLink = createHttpLink({
uri: '/graphql',
headers: {
authorization: localStorage.getItem('token') || ''
}
});
Explanation: This code creates an HTTP link using createHttpLink
from Apollo Client. The link is configured to send requests to the ‘/graphql’ endpoint on the same domain. It also includes an authorization
header with a JWT token retrieved from localStorage.getItem('token')
, or an empty string if the token is not found. This allows the client to send the JWT token along with each request to authenticate with the server.
Authentication and Authorization with JWT in a GraphQL
Authentication and authorization are important aspects of building secure web applications by including those powered by GraphQL. JSON Web Tokens (JWT) provide a popular mechanism for implementing authentication and authorization in GraphQL applications.
In this article, we’ll explore the concepts of authentication and authorization with JWT in a GraphQL application by covering their implementation, and benefits.