Authentication overview

Wikidata, a free and open knowledge base, provides programmatic access to its data primarily through its API and SPARQL endpoint. While public read access to Wikidata's data does not require authentication, any actions that modify data—such as creating or editing items, properties, or lexemes—or require access to user-specific information necessitate authentication. This ensures that all contributions are properly attributed and authorized, maintaining the integrity and collaborative nature of the knowledge base.

The authentication mechanisms for Wikidata are built upon the MediaWiki API, which it inherits. This means developers familiar with MediaWiki's authentication will find similar patterns. The primary methods for authentication involve OAuth 2.0 for applications acting on behalf of users and cookie-based sessions for direct user interactions via web browsers or scripts that emulate browser behavior. Understanding these methods is crucial for developers integrating Wikidata into applications that require write access or personalized features.

Supported authentication methods

Wikidata supports several authentication methods to accommodate different integration scenarios. The choice of method depends on whether the application is a standalone service, a web application, or a script performing specific tasks.

The main authentication methods are:

  • OAuth 2.0: This is the recommended method for third-party applications that need to interact with Wikidata on behalf of a user without storing the user's credentials. OAuth 2.0 provides a secure and standardized way for users to grant limited access to their Wikidata account to applications. The OAuth 2.0 specification details how authorization servers issue access tokens.
  • Cookie-based Sessions: Primarily used for direct user logins through the Wikidata website. This method involves a user logging in via a web interface, which sets a session cookie. Subsequent API requests can then use this cookie to authenticate. It's suitable for scripts that mimic a logged-in user's session or for internal tools.
  • ClientLogin (deprecated for new applications): While still functional for existing integrations, ClientLogin, which involves sending username and password directly, is generally discouraged for new development due to security concerns. It is being phased out in favor of OAuth 2.0.

Here is a summary of the supported authentication methods:

Method When to Use Security Level
OAuth 2.0 Third-party applications, mobile apps, web services acting on behalf of users. High (token-based, user consent, no credential sharing).
Cookie-based Sessions Direct user interaction via web browsers, scripts emulating browser sessions. Medium (reliant on session management and secure cookie handling).
ClientLogin (Legacy) Existing scripts that cannot be migrated to OAuth 2.0. Not recommended for new applications. Low (requires direct credential handling, susceptible to interception without HTTPS).

Getting your credentials

To authenticate with Wikidata, you will typically need to register your application to obtain credentials. The process largely follows the MediaWiki API's approach:

For OAuth 2.0:

  1. Create an account on Wikidata: If you don't already have one, you'll need a user account on Wikidata.
  2. Register your application: Navigate to your user preferences on Wikidata, then find the 'Attached applications' or 'OAuth consumers' section. Here, you can register a new application (consumer). You will need to provide details such as your application's name, description, and a callback URL (for web-based applications).
  3. Obtain Consumer Key and Secret: Upon successful registration, Wikidata will provide you with a Consumer Key (Client ID) and a Consumer Secret (Client Secret). These are your primary credentials for initiating the OAuth flow. Keep your Consumer Secret confidential.
  4. Define scopes: Specify the permissions your application needs (e.g., editpage for editing items, read for reading protected information).

For Cookie-based Sessions:

This method doesn't involve explicit credential generation in the same way as OAuth. Instead, it relies on a user logging into Wikidata through the standard web interface. The session cookie generated during this login can then be used in subsequent API requests. This is typically managed programmatically by making an initial login request to the API, which returns the necessary session tokens and cookies. The Wikidata Data Access documentation provides examples of how to manage sessions.

Authenticated request example

This example demonstrates how to perform an authenticated request using OAuth 2.0, which is the recommended method for most applications. The process generally involves three steps: obtaining an authorized request token, exchanging it for an access token, and then using the access token to make authenticated API calls.

For simplicity, this example illustrates a conceptual flow for making an API request to edit a Wikidata item after an access token has been acquired. The actual OAuth 2.0 flow involves redirects and user consent, which are beyond a simple cURL example.

Assuming you have successfully completed the OAuth 2.0 authorization flow and obtained an access_token and access_secret (for OAuth 1.0a, which MediaWiki uses, though often referred to as OAuth 2.0 in discussions):

# This is a conceptual example for an API edit request using OAuth.
# Actual implementation requires an OAuth library to handle signing and token management.

# Step 1: Get a CSRF token (edit token) for write actions
# This token is required for any action that modifies data to prevent Cross-Site Request Forgery.
# Replace YOUR_ACCESS_TOKEN and YOUR_ACCESS_SECRET with your actual OAuth tokens.

# Using a hypothetical OAuth client that handles the signing:
OAUTH_SIGNATURE_BASE_STRING="POST&https%3A%2F%2Fwww.wikidata.org%2Fw%2Fapi.php&action%3Dquery%26format%3Djson%26meta%3Dtokens%26type%3Dcsrf"

# The actual cURL command would be more complex, including OAuth headers.
# For demonstration, let's assume an OAuth-aware client or library handles the signing.

curl -X POST \
  "https://www.wikidata.org/w/api.php" \
  -H "Authorization: OAuth oauth_consumer_key=\"YOUR_CONSUMER_KEY\", oauth_token=\"YOUR_ACCESS_TOKEN\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1678886400\", oauth_nonce=\"RANDOM_NONCE\", oauth_version=\"1.0\", oauth_signature=\"GENERATED_SIGNATURE\"" \
  -d "action=query" \
  -d "format=json" \
  -d "meta=tokens" \
  -d "type=csrf"

# Response will contain a CSRF token, e.g., "query":{"tokens":{"csrftoken":"YOUR_CSRF_TOKEN+\"}}
CSRF_TOKEN="YOUR_CSRF_TOKEN+\"

# Step 2: Make an authenticated edit request using the CSRF token
# This example modifies an item's description.

# Again, actual cURL command requires OAuth headers and proper signing.
curl -X POST \
  "https://www.wikidata.org/w/api.php" \
  -H "Authorization: OAuth oauth_consumer_key=\"YOUR_CONSUMER_KEY\", oauth_token=\"YOUR_ACCESS_TOKEN\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1678886400\", oauth_nonce=\"ANOTHER_RANDOM_NONCE\", oauth_version=\"1.0\", oauth_signature=\"ANOTHER_GENERATED_SIGNATURE\"" \
  -d "action=wbsetdescription" \
  -d "id=Q12345" \
  -d "language=en" \
  -d "value=An example description" \
  -d "token=$CSRF_TOKEN" \
  -d "format=json"

For practical implementations, it is strongly recommended to use an OAuth library specific to your programming language (e.g., Fetch API in JavaScript, requests-oauthlib in Python) to handle the complexities of OAuth 1.0a signing and token management. The Wikidata Introduction page provides links to further documentation on API usage.

Security best practices

Adhering to security best practices is essential when integrating with Wikidata, especially when your application has write access or handles user data:

  • Use OAuth 2.0 for third-party applications: Always prioritize OAuth 2.0 (or OAuth 1.0a as implemented by MediaWiki) for applications that interact on behalf of users. This prevents your application from needing to store user credentials directly, significantly reducing the risk of compromise.
  • Keep Consumer Secrets confidential: Your OAuth Consumer Secret should be treated like a password. Never embed it directly in client-side code, commit it to public repositories, or transmit it insecurely. Store it in environment variables or a secure configuration management system.
  • Secure your callback URLs: For OAuth applications, ensure your registered callback URLs are secure (use HTTPS) and specific. Avoid using broad wildcards that could be exploited.
  • Request minimal scopes: Follow the principle of least privilege. Only request the specific permissions (scopes) that your application absolutely needs to function. This limits the potential damage if your application's access token is compromised.
  • Implement secure token storage: If your application stores access tokens, ensure they are stored securely. For web applications, secure HTTP-only cookies can be used for session tokens. For server-side applications, encrypt tokens at rest.
  • Validate and sanitize all inputs: When accepting user input that will be used in API calls, always validate and sanitize it to prevent injection attacks (e.g., XSS, SQL injection if constructing SPARQL queries based on input).
  • Use HTTPS for all API communication: All communication with the Wikidata API, whether authenticated or not, should occur over HTTPS to protect data in transit from eavesdropping and tampering.
  • Handle errors gracefully: Implement robust error handling for API responses, especially authentication and authorization errors. Provide informative but not overly detailed error messages to users.
  • Rotate credentials periodically: While not always strictly enforced by Wikidata, it's a good security practice to periodically rotate your OAuth consumer secrets and encourage users to revoke and re-authorize applications.
  • Monitor for suspicious activity: Implement logging and monitoring for your application's interactions with Wikidata. Look for unusual patterns of API calls or failed authentication attempts that could indicate a compromise.