Authentication is a crucial part of APIs, ensuring that only authorized users can access specific resources. In the context of GraphQL APIs, authentication can be implemented in various ways, depending on the needs of your application. This article presents three practical examples for authenticating with a GraphQL API, providing clear use cases and code snippets to illustrate the concepts.
JSON Web Tokens (JWT) are widely used for authentication in web applications. This example demonstrates how to authenticate a user and retrieve a user profile using a GraphQL API with JWT.
The user will first log in, receiving a JWT that will be used in subsequent requests to access protected resources.
## Mutation for user login
mutation Login(\(email: String!, \)password: String!) {
login(email: \(email, password: \)password) {
token
}
}
## Query to get user profile
query GetProfile($token: String!) {
userProfile(token: $token) {
id
name
email
}
}
In this example, the Login
mutation accepts user credentials and returns a JWT token. The GetProfile
query uses this token to retrieve the user’s profile data.
OAuth 2.0 is a common protocol for authorizing third-party applications without exposing user credentials. This example illustrates how to authenticate a user using OAuth 2.0 with a GraphQL API.
In this case, the user will authenticate via a third-party provider (e.g., Google), and the application will receive an access token to use in subsequent API requests.
## Mutation for OAuth login
mutation OAuthLogin(\(provider: String!, \)token: String!) {
oauthLogin(provider: \(provider, token: \)token) {
accessToken
user {
id
name
email
}
}
}
## Example query after authentication
query GetUserData($accessToken: String!) {
userData(accessToken: $accessToken) {
id
preferences
}
}
Here, the OAuthLogin
mutation accepts the provider’s name and the received token, returning an access token for the application. The subsequent GetUserData
query uses this access token to fetch user-specific data.
API keys provide a simple way to authenticate requests. This example shows how to use API keys for authenticating a GraphQL API request. API keys are often used in server-to-server communications or for public APIs.
In this scenario, the client will send an API key as part of the request headers to access a protected resource.
## Query for accessing a resource with API key
query GetData {
data {
id
value
}
}
To use this query, the API key should be included in the request headers:
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
By understanding these examples of authentication with GraphQL API, developers can implement robust security measures in their applications, safeguarding user data while ensuring seamless access to resources.