Authentication
GraphQL Storefront API

Authenticating requests to the GraphQL Storefront API

Authenticate GraphQL Storefront API requests using bearer tokens passed with the Authorization header. You can authenticate using two different kinds of tokens: storefront tokens or customer impersonation tokens.

Example request configuration
POST https://your_store.example.com/graphql
Authorization: Bearer {token}
Accept: application/json
Content-Type: application/json
 
{
  // request body
}

Storefront tokens

Storefront tokens are most appropriate to use directly from the web browser but you can use them in server-to-server communications. If you're creating a token for an application that will make server-to-server or proxied requests to the GraphQL Storefront API, or you work with customer data, use a customer impersonation token. If you only wish to query information from an anonymous shopper's perspective, use a storefront token.

Storefront token security

Generally speaking, vanilla storefront tokens are not considered sensitive, and it is safe to expose them in web browsers. Storefront tokens can only expose information and actions that shoppers can access when they browse a storefront.

It is possible to create a long-lived token that does not expire. For greater security, we recommend creating shorter-lived tokens and rotating them periodically.

For security reasons, GraphQL Storefront API tokens are scoped to particular CORS (opens in a new tab) origins, so you must supply the origin or origins on which you intend to use the token. If you have more than two origins, you will need multiple tokens. If you do not supply any CORS origins, the API will reject requests originating from web browsers, although you can still use it in other contexts. GraphQL server-to-server requests do not require allowed_cors_origins.

Create a storefront token

You can create storefront tokens by API. On Stencil storefronts, you can also access an autogenerated token using in-page context.

Use the Create a storefront token REST endpoint to create storefront bearer tokens. Add the storefront API tokens creation scope to the store-level or app-level API account you use to generate tokens. You can use a storefront bearer token to create a customer access token.

The channel ID for the default Stencil storefront is 1. Storefront tokens don't require you to pass in channel IDs if you want to make the request on behalf of all the stores channels IDs. To learn more about channels, see the channels section of the multi-storefront overview. For more about using the GraphQL Storefront API on custom channels, consult the GraphQL Storefront API overview's FAQ section on alternate channels.

Example request: Create a storefront API token
POST https://api.bigcommerce.com/stores/{{STORE_HASH}}/v3/storefront/api-token
x-auth-token: {{access_token}}
accept: application/json
content-type: application/json
 
{
  "channel_ids": [1, 2, 3],            // array of integers (must be a valid channel IDs on the store)
  "expires_at": 1602288000,   // when the token will expire, as an integer unix timestamp (in seconds)
  "allowed_cors_origins": [   // array of origins (up to 2 origins per token)
    "https://example.com"
  ]
}

Customer access tokens

A customer access token is unique to an individual user's account because it represents an authenticated storefront session for GraphQL requests. You can obtain and use a customer access token only for server-to-server requests. Therefore, you must use the customer access token with a regular storefront token. A customer access token becomes invalid on all devices when you log out of a single device.

⚠️

Do not use this token for browser-side or client-side requests.

Obtaining a customer access token

There are two options to obtain a customer access token.

  1. Login mutation
  2. Login with a JWT
Login mutation

Enter your user email and password to use the login mutation. When using the login mutation in a server-to-server context, the mutation will return a customer access token in response to login actions as part of the GraphQL body instead of a cookie header. From there, you can store the customer access token in the presentation layer's session management system and send it with future GraphQL requests. If the login mutation request is from a browser, we will not return the customer access token in the body, and will instead set a cookie.

Use the Create a Token endpoint to generate the storefront bearer token needed to run the login mutation call. If you still have issues creating a customer access token, we recommend clearing your cookies to resolve any loading issues.

Example login mutation: Create a customer access token
# Creates a customer access token
POST https://{{storeDomain}}/graphql
Authorization: Bearer {Storefront token}
accept: application/json
content-type: application/json
 
mutation Login($email: String!, $pass: String!) {
 login(email: $email, password: $pass) {
   result
   customer {
     entityId
     email
   }
   customerAccessToken {
     value
     expiresAt
   }
 }
}
GraphQL variables
{
"email": "user@email.com", 
"pass": "password"
}
Login with a JWT

The second option is to use the loginWithCustomerLoginJwt mutation to pass your customer JSON web token instead of the user's email and password. In this scenario, you will generate a JWT that contains key information in the payload for the login to be successful. You will use this JWT in the login mutation to receive a customer access token.

For information on creating a JWT, see the Customer Login API article for instructions.

Example JWT login mutation: Create a customer access token
# Creates a customer access token
POST https://{{storeDomain}}/graphql
Authorization: Bearer {Storefront token}
accept: application/json
content-type: application/json
 
mutation Login($jwt: String!) {
 loginWithCustomerLoginJwt(jwt: $jwt) {
   customer {
     entityId
     email
   }
   customerAccessToken {
     value
     expiresAt
   }
 }
}
GraphQL variables
{"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3MjM3Mzc2Y3JiNnJrcTFhY2h3MmdrdTQ2M2FjeGk4IiwiaWF0IjoxNzIwODE0NjgyLCJqdGkiOiJhMDA1OGQ0MC0zNmExLTAxM2ItOTBmNC03ZThiMTE1MDA4YTIiLCJvcGVyYXRpb24iOiJjdXN0b21lcl9sb2dpbiIsInN0b3JlX2hhc2giOiJ3MGFzdGVlOWpvIiwiY3VzdG9tZXJfaWQiOjIyfQ.bfiEpk-IDCqQ4DqpErVCEUUQDjs-vtWxHsEufkUFqMs"
}
Using a Customer Access Token

You can assign the customer access token obtained using one of the mutations described above to the X-Bc-Customer-Access-Token header for future queries. You can use this token for a specific shopper session access until it is invalidated or if it expires due to time. The token is invalidated when you use the logout mutation with the X-Bc-Customer-Access-Token header.

Example customer query
POST https://{{storeDomain}}/graphql
Authorization: Bearer {Storefront token}
X-Bc-Customer-Access-Token: {Customer access token}
accept: application/json
content-type: application/json
 
query CustomerAttributes {
  customer {
    firstName
    lastName
    email
    entityId
    customerGroupId
    attributeCount
    attributes {
      shirtSize: attribute(entityId:123) {
        entityId
        value
      }
      favoriteColor: attribute(entityId:456) {
        entityId
        value
      }
    }
  }
}

Using auto-generated tokens on Stencil storefronts

On Stencil storefronts, you can access a token at render time and pass the token to client-side code using the {{settings.storefront_api.token}} Handlebars property. This auto-generated token has an expiry period of 24-48 hours and will rotate before expiration.

Customer impersonation tokens

⚠️

Because of the flexible use of the customer impersonation token, BigCommerce recommends using a more secure option like the customer access token. Customer impersonation tokens allow you to access any customer by simply changing the X-Bc-Customer-Id value in the header for server-to-server communications. However, the customer access token is tied directly to a specific customer as part of the token payload providing a more secure experience. In addition, customer access tokens have the following added benefits:

  • A customer access token is unique to an individual user's account.
  • A customer access token allows users to act on different systems.
  • A customer access token becomes invalid on all devices when you log out on a single device.

You can use customer impersonation tokens to authenticate requests to the GraphQL Storefront API in server-to-server and headless interactions. The API will reject any customer impersonation token-authenticated requests that originate from a web browser and are not proxied.

⚠️

In the future, we will not support all customer features when using a customer impersonation token. More security-sensitive features will only work with the customer access token. For example, features like exposing a customer's Saved Payment Methods will only work with a customer access token.

Customer impersonation token-authenticated requests will be specific to the customer, including product pricing and availability, customer account details, and more.

It is not necessary to generate a new token for each customer ID. You may use a single token at any given time for your application and specify a distinct customer ID for each set of requests.

Using a customer impersonation token does not automatically sign a customer in. For that, use the customer login mutation or the Customer Login API.

Create a customer impersonation token

Add the Storefront API customer impersonation tokens creation scope to the store-level or app-level API account you use when you Create a customer impersonation token.

Example request: Create a customer impersonation token
POST https://api.bigcommerce.com/stores/{{STORE_HASH}}/v3/storefront/api-token-customer-impersonation
X-Auth-Token: {{access_token}}
Accept: application/json
Content-Type: application/json
 
{
  "channel_ids": [1, 2, 3] // array of integers (must be a valid channel IDs on the store)
  "expires_at": 1602288000 // when the token will expire, as an integer unix timestamp (in seconds)
}

Customer impersonation token security

Unlike storefront API tokens, customer impersonation tokens are sensitive and should never be exposed publicly. Treat them with the same care as other application secrets, such as API account access tokens.

If your token is compromised, you can use the Revoke a token endpoint. Only use this in emergencies; do not revoke tokens unnecessarily. Instead, use a shorter expiration and allow them to expire naturally.

Signing customers in

A customer can only sign in on one device. When you run the customer login mutation for a session on a new device, the customer is automatically signed out of the previous session.

If you're using the GraphQL Storefront API from a browser, for example, on top of your Stencil storefront, you can use the login mutation to sign in to a customer account with an email address and a password. This will set a session cookie in the browser, which will authenticate the customer account on future requests. You can also perform a login operation by passing the guestCartEntityID variable and assigning a cart to a customer.

This mutation is also useful for server-to-server or headless storefront applications that use a customer impersonation token. For example, you can use a sign in form to validate a customer's email address and password. When the mutation returns successfully, you can take the resulting customer ID and store it in a session to pass with the X-Bc-Customer-Id header.

As a security best practice, you should inject the email address and password using GraphQL query variables. This prevents the password from being exposed in the query itself. In the GraphQL Storefront playground, you can set variables for requests.

GraphQL Storefront playground query variables

⚠️

In the customer login mutation, the result field is deprecated. Instead, request customer object information.

Login mutation request
  POST https://your_store.example.com/graphql
  Accept: application/json
  Content-Type: application/json
  Authorization: Bearer {token}

Signing customers out

You can use the logout mutation to sign out of a customer account. If you're using a vanilla storefront token, future requests in that shopper's session will be from the perspective of an anonymous shopper.

Example query: logout mutation
mutation Logout {
  logout {
    result
  }
}

Further reading

Endpoints

Did you find what you were looking for?