Authentication overview
Authentication for the Shopify Admin API is the process by which an application verifies its identity and gains authorized access to a Shopify store's data and administrative functions. The Shopify Admin API supports different authentication mechanisms depending on the type of application being developed: public apps, custom apps, or private apps. Each method is designed to provide secure access while aligning with the specific deployment and usage patterns of the application.
For applications that serve multiple merchants and are listed on the Shopify App Store, OAuth 2.0 is the standard. This protocol allows merchants to grant explicit permissions to an application without sharing their credentials directly with the application, aligning with industry best practices for delegated authorization as outlined by the OAuth 2.0 specification. Custom apps, developed for a single merchant but requiring broader distribution within their organization, also utilize OAuth 2.0. Private apps, intended for exclusive use by a single store owner or their development team, rely on API access tokens for direct, simplified authentication.
The choice of authentication method dictates the credential management, authorization flow, and scope of access an application will have. Understanding these distinctions is crucial for designing secure and functional integrations with the Shopify Admin API.
Supported authentication methods
The Shopify Admin API primarily supports two distinct authentication approaches: OAuth 2.0 and API access tokens. The appropriate method depends on the application's nature and target audience.
OAuth 2.0
OAuth 2.0 is the recommended protocol for applications that interact with multiple Shopify stores or require merchant consent for access. This includes:
- Public Apps: Applications published on the Shopify App Store, accessible to any merchant.
- Custom Apps: Applications built for a specific merchant but intended for broader use within their organization, often developed by agencies or large businesses.
The OAuth 2.0 flow involves several steps:
- Authorization Request: Your application redirects the merchant to Shopify's authorization URL, requesting specific access scopes (permissions like
read_productsorwrite_orders). - Merchant Consent: The merchant reviews the requested permissions and grants consent.
- Authorization Code: Shopify redirects the merchant back to your application with an authorization code.
- Access Token Request: Your application exchanges the authorization code for an access token by making an API call to Shopify's token endpoint, securely using its client ID and client secret.
- API Access: Your application uses the obtained access token (a bearer token) to make authenticated requests to the Shopify Admin API.
This method ensures that sensitive merchant credentials are never exposed to the application, and access can be revoked by the merchant at any time. For a detailed guide on implementing OAuth, refer to the Shopify OAuth documentation.
API Access Tokens (Private Apps)
API access tokens are used for private apps, which are built exclusively for a single Shopify store. These are suitable for:
- Internal Tools: Scripts or applications developed by a store owner for their own administrative purposes.
- One-off Integrations: Custom solutions that only need to interact with a specific store.
With private apps, access tokens are generated directly within the Shopify Admin interface. Once generated, these tokens grant direct access to the store's API endpoints, based on the permissions assigned during token creation. Private app authentication is simpler, as it bypasses the OAuth redirect flow:
- Token Generation: The store owner creates a private app in their Shopify Admin, specifying the required API permissions.
- Direct Usage: The generated API access token is then used directly in the
X-Shopify-Access-Tokenheader for each API request.
While simpler, this method requires careful handling of the access token, as its compromise grants direct access to the store's data up to the assigned scopes.
Comparison of Authentication Methods
The following table summarizes the key characteristics of each authentication method:
| Method | When to Use | Security Level | Credential Type | Authorization Flow |
|---|---|---|---|---|
| OAuth 2.0 | Public apps, custom apps, multi-merchant solutions | High (delegated access, token exchange) | Client ID, Client Secret | Authorization Code Grant |
| API Access Token | Private apps, single-store internal tools | Moderate (direct token usage, requires secure storage) | API Access Token | Direct (pre-generated) |
Getting your credentials
The process for obtaining credentials varies based on whether you are building a public/custom app (using OAuth 2.0) or a private app (using an API access token).
For Public and Custom Apps (OAuth 2.0)
- Create a Partner Account: If you don't already have one, sign up for a Shopify Partner account. This is required to develop and manage apps.
- Create a New App: From your Partner Dashboard, navigate to Apps and click Create app. Choose either Public app or Custom app.
- Configure App Details: Provide a name for your app, a URL where your app is hosted (App URL), and a list of Allowed redirection URLs (where Shopify will send the merchant after authorization).
- Retrieve Client ID and Client Secret: After creating the app, Shopify will provide you with a unique Client ID (API key) and a Client Secret (API secret key). These are critical for the OAuth handshake.
- Define Access Scopes: In your app settings, specify the required access scopes (permissions) that your app needs to function. These will be presented to the merchant during the authorization process.
For Private Apps (API Access Token)
- Access Shopify Admin: Log in to the Shopify Admin for the specific store you want to integrate with.
- Navigate to Apps: Go to Apps in the left sidebar.
- Develop Apps: Click on Develop apps, then Create an app.
- Name the App: Give your private app a descriptive name.
- Configure API Scopes: Under the API scopes section, select the necessary permissions that your app will require.
- Install App: Click Install app. This will generate your API access token.
- Retrieve API Access Token: After installation, you will be presented with the Admin API access token. This token is shown only once, so copy it immediately and store it securely.
Authenticated request example
Once you have obtained an access token (either via OAuth 2.0 or as a private app token), you can use it to make authenticated requests to the Shopify Admin API. All requests must be made over HTTPS.
The access token is typically included in the X-Shopify-Access-Token header for private apps or in the Authorization header with a Bearer prefix for OAuth 2.0 tokens.
Example using a Private App API Access Token (Node.js)
This example demonstrates fetching a list of products using a private app's API access token.
const fetch = require('node-fetch');
const shopifyStoreUrl = 'YOUR_STORE_NAME.myshopify.com';
const accessToken = 'YOUR_PRIVATE_APP_ACCESS_TOKEN';
async function getProducts() {
try {
const response = await fetch(`https://${shopifyStoreUrl}/admin/api/2024-04/products.json`, {
method: 'GET',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Products:', data.products);
} catch (error) {
console.error('Error fetching products:', error);
}
}
getProducts();
Example using an OAuth 2.0 Bearer Token (Python)
This example shows how to make an authenticated request using an OAuth 2.0 generated access token.
import requests
shopify_store_url = 'YOUR_STORE_NAME.myshopify.com'
access_token = 'YOUR_OAUTH_BEARER_TOKEN'
api_version = '2024-04'
def get_orders():
url = f"https://{shopify_store_url}/admin/api/{api_version}/orders.json"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
orders = response.json()
print("Orders:", orders['orders'])
except requests.exceptions.RequestException as e:
print(f"Error fetching orders: {e}")
get_orders()
Always replace placeholder values like YOUR_STORE_NAME.myshopify.com, YOUR_PRIVATE_APP_ACCESS_TOKEN, and YOUR_OAUTH_BEARER_TOKEN with your actual store URL and credentials.
Security best practices
Implementing robust security measures is paramount when interacting with the Shopify Admin API to protect sensitive merchant and customer data.
- Secure Credential Storage: Never hardcode API access tokens, client secrets, or refresh tokens directly into your application's source code. Use environment variables, secure configuration files, or dedicated secret management services (e.g., Google Cloud Secret Manager, AWS Secrets Manager) to store credentials.
- Use HTTPS Everywhere: Ensure all communication with the Shopify Admin API occurs over HTTPS to encrypt data in transit and prevent eavesdropping. Shopify enforces HTTPS for all API endpoints.
- Least Privilege Principle: Request only the minimum necessary access scopes for your application to function. Over-privileged applications pose a greater security risk if compromised. Regularly review and update scopes as your application's requirements evolve.
- Token Expiration and Rotation: For OAuth 2.0, leverage refresh tokens to obtain new access tokens periodically. Implement mechanisms to automatically refresh tokens before they expire. While private app tokens do not expire, consider rotating them periodically by generating a new token and revoking the old one.
- Input Validation and Sanitization: Validate and sanitize all data received from API responses and user input before processing it. This helps prevent common vulnerabilities like injection attacks.
- Rate Limit Handling: Implement proper rate limit handling with exponential backoff and retry mechanisms to avoid overwhelming the API and getting your application temporarily blocked.
- Error Handling and Logging: Implement comprehensive error handling and logging for API interactions. Log authentication failures, unauthorized access attempts, and other security-related events to facilitate auditing and incident response.
- Protect Redirect URIs: For OAuth 2.0 apps, ensure your Allowed redirection URLs are correctly configured and secured. Only allow redirects to trusted domains controlled by your application to prevent open redirect vulnerabilities.
- Monitor for Suspicious Activity: Regularly monitor your application's logs for unusual patterns of API usage or repeated authentication failures, which could indicate a security incident.