GraphQL Authentication on BigCommerce

Rachael Thompson
BigCommerce Developer Blog
5 min readAug 24, 2021

GraphQL applies query logic to our BigCommerce Storefront APIs making it faster and more performant to get a lot of data for your frontend application or to power Stencil storefronts. By utilizing queries we are able to get a lot more data from multiple endpoints at one time. We are therefore able to support more use cases a developer might be solving for. This also means you can deal with Cross Origin Resource Sharing (CORS) less by authenticating a complex GraphQL request over multiple REST requests. Taking this into account, GraphQL authentication on BigCommerce is a smooth and standard process that follows industry best practices. Utilizing the BigCommerce Storefront GraphQL API doesn’t need to be intimidating or scary. We will go over the basic authentication and customer impersonation and use cases for utilizing this modern and fun API.

The BigCommerce GraphQL Stack

Here at BC, our GraphQL development is written in Scala. We utilize a Scala library known as Sangria. We enable our technology partners and developers to interact with our GraphQL implementation by utilizing GraphQL Explorer and GraphQL Playground. We also leverage JSON Web Tokens (JWT) for authorizing your acceptable use of this API.

Using the GraphQL Explorer and Playground.

These tools serve as documentation of our Storefront GraphQL implementation as well as a way you can begin to interact with the data contained in a storefront. The GraphQL Explorer is great for seeing the relationships between objects in the GraphQL API. The GraphQL Playground has documentation as well as example queries that you can use to learn.

You can see the use of a JWT in the GraphQL Playground as well. It is under HTTP HEADERS of which there is only one by default, authorization. In this array or key-value pairs authorization key has a valued pair that is a bearer token. This bearer token is a JWT for the storefront you are accessing.

🧠 You can always use a tool like JWT.io to decode and validate your token. This is what the token from our Dev Docs looks like decoded.

Authenticating using a JSON Web Token (JWT)

In order to use the Storefront GraphQL API, we should first request a token from BigCommerce. The Storefront GraphQL Overview is a great place to review this information. As previously noted, the JWT is sent as a bearer token in the authorization header value. You can request a token using a POST request to the `api-token` endpoint.

POST https://api.bigcommerce.com/stores/{store_hash}/v3/storefront/api-token
{
“channel_id”: 1, // int (must be a valid channel ID on the store)
“expires_at”: 1602288000, // double utc unix timestamp (required)
“allowed_cors_origins”: [ // array (accepts 1 origin currently)
“https://example.com”
]
}

📓 Note:

  • You will need to include the `channel_id` in the request body especially for headless storefronts.
  • You can learn more about channels by visiting the Channels Toolkit docs.
  • You will also want to make sure that any custom domain(s) are listed in your `allowed_cors_origins`.
  • This requires a request per domain or subdomain.

The response will return the token and any metadata.

{
“token”:”…eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9…”,
“meta”: {
// …
}
}

Requesting a Stencil Authorization Token

Stencil Storefronts leverage Handlebars syntax. Using the {{settings.storefront_api.token}} injected in your POST request for the data you are requesting.

Here is an example from our dev docs that highlights how to leverage handlebars and add a storefront query.

fetch(‘/graphql’, {
method: ‘POST’,
credentials: ‘same-origin’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: ‘Bearer {{settings.storefront_api.token}}’
‘’
},
body: JSON.stringify({ query: `query MyFirstQuery {…}`
);

📓 Additional Notes:

  • By default the store’s Stencil channel_id is set to [1].
  • The `/storefront/api-token` endpoint requires the “Manage Storefront API Tokens” OAuth Scope.
  • The fetch request credentials property must be set to the same-origin (even when making a request from a Stencil theme).

Authenticating a Customer

Using the Customer Login Mutation

This mutation allows you to authenticate a user. From any user interface with inputs, you can have the customer enter their email and password, post this mutation and the response will return true/false and if true can return the customer object. This will also set a session cookie to continue authenticating the user.

mutation Login($email: String!, $pass: String!) {
login(email: $email, password: $pass) {
result
}
}

📓 Note: As a best practice, you should only inject sensitive information like the password using a GraphQL query variable. This prevents the sensitive data from being exposed in the query itself.

Below shows some of the information you can expect the returned customer to have.

Using a Customer Impersonation token

Most teams use impersonation tokens as a means to troubleshoot or debug systems similar to the way an actual user would interact with them. The same is true for Customer Impersonation. You are impersonating the role and privileges of a given custom. You pass a customer ID in the header of the request and are returned a token that will let you act within the application as the customer for the given ID.

POST https://api.bigcommerce.com/stores/{store_id}/v3/storefront/api-token-customer-impersonationX-Auth-Token: {{ACCESS_TOKEN}}Content-Type: application/jsonAccept: application/json
X-Bc-Customer-Id: {{CUSTOMER_ID}}
{
“channel_id”: 1,
“expires_at”: 1602288000
}

The response should return:

{
“data”:
{
“token”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c”
}
“meta”: {}
}

This feature can be especially helpful to app developers as this unlocks server to server capabilities with a trusted consumer. So consider using this feature in your server side applications that interface with a BigCommerce storefront.

You’re Authenticated

So why should you use GraphQL authorization and authentication? It is simple: simple API calls, simple returns, and simple tokens. GraphQL simplifies frontend requests and responses making for a better developer experience. You can request more specific data from a single endpoint than with our REST API offering and have more distinct returns than when utilizing REST. This can be extremely useful with applications that leverage our frontend but have a backend server component.

Now that you are authenticated, reach for the BigCommerce GraphQL API when developing:

  • Storefronts in either Stencil or a headless implementation.
  • When developing customized user interfaces leveraging customer data.
  • When you need to impersonate a user.
  • When you want to have finer control of returned data.

If you need support or want to chat about the GraphQL API offering you can connect with us @BigCommerceDevs on Twitter, or in our community spaces.

👋 Happy Coding! 🖥

--

--