Authentication overview

Wiktionary, a multilingual dictionary project of the Wikimedia Foundation, provides its content freely and openly. Unlike many commercial APIs that require authentication for basic read access, Wiktionary's core data is designed for public consumption without explicit authentication for simple retrieval. Programmatic access to Wiktionary's vast linguistic data is primarily facilitated through the MediaWiki API, which is the underlying infrastructure for all Wikimedia projects, including Wikipedia and Wiktionary.

Authentication becomes necessary when a user or application needs to perform actions that modify Wiktionary content, such as editing entries, creating new pages, or managing user-specific preferences through the API. For these write operations, the MediaWiki API supports several authentication mechanisms to ensure that only authorized users can make changes. This approach maintains the integrity and security of the collaborative editing environment while keeping the content accessible to all.

Developers integrating with Wiktionary's data should understand that they are interacting with the broader Wikimedia ecosystem. Therefore, authentication processes and best practices align with those established for the MediaWiki platform. This includes adherence to Wikimedia's API usage policies and rate limits, which are designed to prevent abuse and ensure equitable access for all users.

Supported authentication methods

The Wikimedia API, which serves Wiktionary content, supports several authentication methods, each suitable for different use cases. The choice of method depends on whether the application needs to act on behalf of a user, perform automated tasks, or simply read public data.

Method When to Use Security Level
No Authentication Accessing public, read-only data; anonymous queries. N/A (no credentials exchanged)
OAuth 1.0a Third-party applications acting on behalf of a user (e.g., an app that edits Wiktionary on a user's behalf). Recommended for most user-facing applications requiring authenticated access. High (secure token exchange, user consent)
Bot Passwords Automated scripts or bots performing specific, limited actions without full user account access. Offers fine-grained permissions. Medium-High (specific permissions, revocable)
Session Cookies Web applications or scripts running on the same domain as Wiktionary, typically for logged-in user sessions. Less common for external API integrations. Medium (tied to browser session, potentially less secure for external bots)

OAuth 1.0a

OAuth 1.0a is the recommended method for third-party applications that need to interact with Wiktionary on behalf of a user. It provides a secure delegated authorization flow, allowing users to grant an application specific permissions without sharing their account credentials. The Wikimedia OAuth implementation follows the OAuth 1.0a specification, involving consumer keys, consumer secrets, request tokens, and access tokens.

Bot Passwords

For automated scripts or bots that need to perform specific, often repetitive, actions, Bot Passwords offer a more secure alternative to using a full user account's password. A bot password is a unique, randomly generated credential that can be created for a specific purpose and granted limited permissions (e.g., edit pages, upload files). If compromised, only the actions permitted by that specific bot password are at risk, and it can be revoked independently without affecting the main user account.

Session Cookies

While technically a form of authentication, using session cookies is generally not recommended for external API integrations. This method is primarily used by web browsers when a user logs into Wiktionary directly. For programmatic access, especially from external applications, OAuth or Bot Passwords provide a more robust and secure framework.

Getting your credentials

The process of obtaining credentials depends on the chosen authentication method for interacting with Wiktionary via the Wikimedia API.

For OAuth 1.0a

  1. Register your application: Navigate to the Wikimedia OAuth consumer registration page. You will need to provide details about your application, including its purpose, callback URL, and requested permissions.
  2. Receive Consumer Key and Secret: Upon successful registration and approval, your application will be issued a Consumer Key and a Consumer Secret. These are unique identifiers for your application.
  3. Implement the OAuth flow: Your application will then initiate the OAuth 1.0a flow, which involves obtaining a request token, redirecting the user to Wiktionary for authorization, and finally exchanging the authorized request token for an access token and access token secret. These access tokens are specific to the user and your application, allowing you to make authenticated requests on their behalf.

For Bot Passwords

  1. Log in to your Wiktionary account: Access your user preferences on Wiktionary.
  2. Generate a Bot Password: Go to the Special:BotPasswords page (or similar in your user preferences).
  3. Define Permissions: Specify the exact permissions your bot needs (e.g., 'Edit pages', 'Upload files'). Granting only necessary permissions adheres to the principle of least privilege.
  4. Create and Store: Generate the bot password. You will be provided with a unique username and password combination. Store these credentials securely, as they will not be displayed again.

Authenticated request example

Since direct authentication to Wiktionary is via the MediaWiki API, an example authenticated request would typically involve using OAuth 1.0a or Bot Passwords for write operations. Here's a conceptual example using a Bot Password to make a simple edit via the MediaWiki API. This example assumes you have already obtained a Bot Password (username and password).

Example: Editing a Wiktionary page using a Bot Password (conceptual Python example)

import requests

API_URL = "https://en.wiktionary.org/w/api.php"
BOT_USERNAME = "YourBotUsername"
BOT_PASSWORD = "YourBotPassword"

# Step 1: Login to get a session token (for write actions)
def login(username, password):
    session = requests.Session()
    login_params = {
        "action": "login",
        "lgname": username,
        "lgpassword": password,
        "format": "json"
    }
    response = session.post(API_URL, data=login_params)
    login_data = response.json()

    if login_data["login"]["result"] == "Success":
        print("Login successful!")
        return session, login_data["login"]["token"]
    else:
        print(f"Login failed: {login_data['login']['reason']}")
        return None, None

# Step 2: Get a CSRF token for the edit
def get_csrf_token(session):
    token_params = {
        "action": "query",
        "meta": "tokens",
        "type": "csrf",
        "format": "json"
    }
    response = session.get(API_URL, params=token_params)
    return response.json()["query"]["tokens"]["csrftoken"]

# Step 3: Perform the edit
def edit_page(session, title, text, summary, token):
    edit_params = {
        "action": "edit",
        "title": title,
        "text": text,
        "summary": summary,
        "token": token,
        "format": "json"
    }
    response = session.post(API_URL, data=edit_params)
    edit_data = response.json()
    if "edit" in edit_data and "result" in edit_data["edit"] and edit_data["edit"]["result"] == "Success":
        print(f"Page '{title}' edited successfully.")
    else:
        print(f"Edit failed: {edit_data}")

# Main execution
if __name__ == "__main__":
    session, login_token = login(BOT_USERNAME, BOT_PASSWORD)
    if session and login_token:
        csrf_token = get_csrf_token(session)
        if csrf_token:
            page_title = "Test_Page_for_API_Edit"
            new_text = "This is a test edit from a bot. " + \
                         "Adding current timestamp: " + \
                         datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            edit_summary = "Bot test edit via API"
            edit_page(session, page_title, new_text, edit_summary, csrf_token)
        else:
            print("Failed to get CSRF token.")

This example demonstrates the multi-step process for authenticated write operations: logging in with bot credentials to establish a session, obtaining a CSRF token for security, and then executing the edit. For a comprehensive guide on MediaWiki API requests, consult the official MediaWiki API documentation.

Security best practices

When integrating with Wiktionary via the Wikimedia API, adhering to security best practices is crucial to protect both your application and the integrity of the Wiktionary project.

  • Principle of Least Privilege: Grant only the minimum necessary permissions to your application or bot. If a bot only needs to read pages, do not give it editing permissions. For Bot Passwords, this means carefully selecting the capabilities during creation.
  • Secure Credential Storage: Never hardcode API keys, secrets, or bot passwords directly into your source code. Use environment variables, secure configuration files, or dedicated secret management services (e.g., AWS Secrets Manager, Google Secret Manager) to store and retrieve credentials securely.
  • Protect OAuth Secrets: For OAuth 1.0a, ensure your Consumer Secret is never exposed client-side. All OAuth token exchange should occur on a secure server-side environment.
  • HTTPS Everywhere: Always use HTTPS for all API communications to encrypt data in transit and prevent man-in-the-middle attacks. The Wikimedia API strictly enforces HTTPS.
  • Rate Limiting and Error Handling: Implement robust rate-limiting logic in your application to avoid overwhelming the API servers. Handle API errors gracefully, including those related to authentication failures or rate limit breaches, to prevent unexpected behavior or service interruptions.
  • Regular Credential Rotation: Periodically rotate bot passwords and OAuth consumer secrets to minimize the risk associated with long-lived credentials. If a credential is suspected of being compromised, revoke it immediately.
  • Monitor and Audit: Implement logging and monitoring for your application's API interactions. This allows you to detect unusual activity, such as a high volume of failed authentication attempts or unauthorized actions, which could indicate a security incident.
  • User Agent Identification: Always include a descriptive User-Agent header in your API requests, identifying your application. This helps Wikimedia administrators understand the source of traffic and contact you if issues arise.
  • Stay Updated: Keep your libraries and frameworks used for API interaction up to date to benefit from the latest security patches and improvements.