Authentication overview

The Unsplash API requires authentication for all requests to ensure proper usage tracking, rate limiting, and secure access to its image library and user-specific functionalities. Unsplash employs two distinct authentication mechanisms to cater to different types of API interactions: API keys for accessing public data and OAuth 2.0 for actions that require user consent or involve user-specific data. Understanding when to use each method is crucial for integrating the Unsplash API effectively into an application.

API keys are suitable for applications that primarily fetch public images, search for photos, or retrieve collection details without needing to interact with a user's personal Unsplash account. These keys are typically passed as a header or query parameter with each request. OAuth 2.0, on the other hand, is designed for scenarios where an application needs to perform actions on behalf of a Unsplash user, such as uploading photos, liking images, or accessing private collections. This method involves a multi-step authorization flow where the user grants explicit permission to the application.

Both methods rely on secure communication channels, specifically HTTPS/TLS, to protect credentials and data in transit. Adhering to Unsplash's authentication guidelines and general security best practices is essential for maintaining the integrity and availability of your application while interacting with the Unsplash platform, as outlined in the official Unsplash API documentation.

Supported authentication methods

Unsplash primarily supports two authentication methods for its API:

  1. API Key (Client-ID): This is the most straightforward method for accessing public data. It involves generating a unique key for your application and including it with every API request. This method is suitable for read-only operations that do not require user-specific permissions.
  2. OAuth 2.0: This is an industry-standard protocol for authorization and is used when your application needs to access a user's private data or perform actions on their behalf (e.g., liking a photo, uploading a photo). OAuth 2.0 involves a multi-step flow where the user grants your application specific permissions. The OAuth 2.0 specification is maintained by the IETF.

The choice between these methods depends on the functionality your application requires. For simple public data retrieval, an API key is sufficient. For any interaction involving user accounts or private data, OAuth 2.0 is mandatory.

Unsplash API Authentication Methods
Method When to Use Security Level
API Key (Client-ID) Accessing public data (e.g., searching photos, fetching public collections) Moderate (protect key from exposure)
OAuth 2.0 Performing actions on behalf of a user (e.g., liking photos, uploading, accessing private data) High (requires user consent, token-based authorization)

Getting your credentials

To interact with the Unsplash API, you first need to register an application and obtain the necessary credentials. This process is managed through the Unsplash developer portal.

For API Keys (Client-ID)

  1. Create an Unsplash Account: If you don't already have one, sign up for a free Unsplash account on their homepage.
  2. Register Your Application: Navigate to the Unsplash Developers page and click on "Your apps" or "New Application".
  3. Provide Application Details: Fill in the required information, including your application's name, description, website URL, and a callback URL (if you plan to use OAuth later).
  4. Accept Terms: Read and agree to the Unsplash API Terms of Use.
  5. Obtain Your Access Key: Once registered, your application will be assigned a unique "Access Key" (also referred to as Client-ID). This key is your API key for public data access. Keep this key secure.

For OAuth 2.0

Implementing OAuth 2.0 requires an additional step beyond just obtaining an Access Key. You will also use a "Secret Key" and configure redirect URIs.

  1. Register as above: Follow steps 1-4 for API Keys to register your application. Your application will also be assigned a "Secret Key" in addition to the "Access Key".
  2. Configure Redirect URI(s): In your application settings on the Unsplash developer dashboard, specify one or more "Redirect URIs". These are the URLs to which Unsplash will redirect the user after they have authorized your application. They must exactly match the URI used in your OAuth authorization request.
  3. Implement the OAuth Flow: Your application will need to initiate the OAuth 2.0 authorization flow, typically involving these steps, as detailed in the Unsplash OAuth documentation:
    • Redirect the user to the Unsplash authorization URL with your Client-ID, redirect URI, and requested scopes.
    • The user grants or denies permission on Unsplash's website.
    • Unsplash redirects the user back to your specified Redirect URI with an authorization code.
    • Your application exchanges this authorization code for an access token (and refresh token) by making a server-side request to Unsplash's token endpoint, using your Client-ID and Secret Key.
    • Use the access token to make authenticated API requests on behalf of the user.

Authenticated request example

Here are examples of how to make authenticated requests using both an API Key and an OAuth 2.0 access token.

Using an API Key (Client-ID)

For public data access, you typically include your Access Key (Client-ID) in the Authorization header or as a query parameter. The Unsplash documentation recommends using the Authorization header with the Client-ID prefix.

Example: Fetching a random photo

curl -X GET "https://api.unsplash.com/photos/random"
     -H "Authorization: Client-ID YOUR_ACCESS_KEY"
import requests

access_key = "YOUR_ACCESS_KEY"
headers = {
    "Authorization": f"Client-ID {access_key}"
}

response = requests.get("https://api.unsplash.com/photos/random", headers=headers)
print(response.json())

Using an OAuth 2.0 Access Token

Once you have obtained an OAuth 2.0 access token, you include it in the Authorization header with the Bearer prefix for requests requiring user authorization.

Example: Liking a photo

curl -X POST "https://api.unsplash.com/photos/PHOTO_ID/like"
     -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
import requests

access_token = "YOUR_OAUTH_ACCESS_TOKEN"
photo_id = "PHOTO_ID"
headers = {
    "Authorization": f"Bearer {access_token}"
}

response = requests.post(f"https://api.unsplash.com/photos/{photo_id}/like", headers=headers)
print(response.json())

Security best practices

Implementing robust security measures is paramount when working with API credentials, especially for an API like Unsplash that can involve both public data and user-specific actions. Adhering to these best practices will help protect your application and your users.

  • Protect Your API Keys and Secrets: Never hardcode your Access Key or Secret Key directly into client-side code (e.g., JavaScript in a browser). For Client-IDs used in client-side applications, ensure they are not easily discoverable or exploitable. For Secret Keys, which should always remain confidential, store them in environment variables or a secure configuration management system on your server. Avoid committing them to version control systems like Git. The Mozilla Developer Network's guide to environment variables provides more information on secure storage.
  • Use HTTPS/TLS Everywhere: Always ensure that all communication with the Unsplash API occurs over HTTPS (TLS). This encrypts data in transit, protecting your API keys, access tokens, and user data from interception by malicious actors. Unsplash enforces HTTPS for its API endpoints.
  • Implement OAuth 2.0 Securely: When using OAuth 2.0, correctly implement the authorization flow. Use a strong state parameter to prevent Cross-Site Request Forgery (CSRF) attacks. Validate redirect URIs strictly to prevent open redirect vulnerabilities. Never expose your OAuth client_secret on the client-side.
  • Manage Access Tokens and Refresh Tokens: Store access tokens securely on the server-side, and refresh them before they expire. Use refresh tokens to obtain new access tokens without requiring the user to re-authorize, but also store refresh tokens securely and revoke them if compromised.
  • Apply Principle of Least Privilege: Request only the necessary OAuth scopes from users. For example, if your application only needs to read public photos, do not request scopes that allow uploading or modifying user data. This limits the potential damage if your application's access token is compromised.
  • Monitor API Usage: Regularly monitor your API usage patterns for any unusual activity that might indicate unauthorized access or abuse of your credentials. Unsplash provides rate limiting, and exceeding these limits might be a sign of compromised keys.
  • Rotate Credentials: Periodically rotate your API keys and client secrets. This reduces the window of opportunity for an attacker if credentials are leaked.
  • Error Handling and Logging: Implement robust error handling for API authentication failures. Log authentication attempts and failures to help detect and diagnose security incidents, but be careful not to log sensitive information like raw API keys or tokens.