Authentication overview
The Wikipedia API, powered by the MediaWiki API, provides programmatic access to Wikipedia's vast content and functionality. For most read-only operations, such as fetching page content or querying article metadata, no authentication is required. This allows for broad public access to Wikipedia's knowledge base without the need for API keys or user logins. However, for operations that modify Wikipedia content (e.g., editing pages, uploading files), accessing user-specific data, or performing actions on behalf of a registered Wikipedia user, authentication is mandatory. This ensures accountability, prevents unauthorized changes, and protects user privacy.
The authentication mechanisms primarily cater to two distinct use cases: registered Wikipedia users interacting with the API (often through web applications) and automated bots or third-party applications performing actions on a user's behalf or their own. Understanding the specific requirements for your application's interaction with Wikipedia is crucial for selecting the appropriate authentication method and implementing it securely.
Supported authentication methods
The MediaWiki API supports several authentication methods to accommodate different application types and security needs. The choice of method depends on whether your application is acting on behalf of a user, is a standalone bot, or requires specific privileges.
| Method | When to Use | Security Level |
|---|---|---|
| OAuth 2.0 | Third-party applications requiring user authorization for actions (e.g., editing, watchlist management). Recommended for most web and mobile applications. | High. Delegates limited access without sharing user credentials. Uses tokens that can be revoked. |
| Cookie-based Authentication (Login) | Scripts or bots running directly on a Wikipedia user's behalf, typically for automated tasks where a user explicitly logs in. Less common for external applications. | Medium. Requires handling session cookies. Susceptible to session hijacking if not managed carefully. |
| Bot Passwords | Dedicated bots or scripts performing automated tasks. Provides a separate, revocable password for API access, distinct from the user's main account password. | High. Granular permissions can be set. Passwords can be easily revoked without affecting the main user account. |
| No Authentication | Read-only access to public content (e.g., retrieving page text, querying categories). | N/A. No user-specific data or write operations involved. |
OAuth 2.0
OAuth 2.0 is the recommended authentication method for most third-party applications that need to interact with Wikipedia on behalf of a user. It provides a secure and standardized way for users to grant limited access to their Wikipedia account data and functionality without sharing their login credentials directly with the application. The MediaWiki API implements the OAuth 2.0 authorization framework, allowing applications to request specific permissions (scopes) from users, such as editing pages or managing watchlists. Developers must register their application to obtain client credentials before initiating the OAuth flow.
Cookie-based Authentication
For scripts or tools that require a direct user login, the MediaWiki API supports cookie-based authentication. This involves making a login request to the API with a username and password, which returns session cookies. Subsequent requests then include these cookies to maintain the authenticated session. This method is generally used for internal tools or personal scripts rather than public-facing applications due to the direct handling of user credentials. Developers can find details on cookie-based login in the MediaWiki API documentation.
Bot Passwords
Bot passwords offer a secure alternative for automated scripts and bots. A bot password is a unique, randomly generated password associated with a user's account but distinct from their main login password. It can be configured with specific permissions (e.g., only edit certain namespaces) and can be revoked independently. This minimizes the risk associated with compromised credentials, as a bot password only grants limited access. Users can create and manage bot passwords through their Wikipedia preferences.
Getting your credentials
The process for obtaining credentials varies depending on the chosen authentication method:
For OAuth 2.0 applications
- Register your application: Navigate to the Wikimedia OAuth consumer registration page. You will need to provide details about your application, including its name, description, and the callback URLs.
- Obtain client key and secret: Upon successful registration, you will be issued a client key (consumer key) and a client secret (consumer secret). These credentials identify your application to the OAuth provider.
- Define scopes: Determine the specific permissions (scopes) your application needs (e.g.,
editfor editing pages,readfor general access).
For cookie-based authentication
No specific credentials need to be pre-generated. You will use a Wikipedia username and password directly in the API login request. This method is generally discouraged for public applications due to security implications.
For bot passwords
- Log in to Wikipedia: Access your Wikipedia account.
- Navigate to preferences: Go to your user preferences and locate the "Bot passwords" section.
- Create a new bot password: Follow the instructions to create a new bot password. You will be prompted to name the bot password and define its permissions (e.g., which actions it can perform, which namespaces it can access).
- Record the password: The system will generate a unique bot password. Make sure to record it securely, as it will not be shown again.
Authenticated request example
Here's an example of how to make an authenticated request using a bot password with Python. This example uses the requests library for HTTP requests, assuming you have a bot password set up with editing permissions. For OAuth 2.0, you would typically use an OAuth client library to manage token exchange and signing.
import requests
# Replace with your actual bot username and bot password
BOT_USERNAME = 'YourBotUsername'
BOT_PASSWORD = 'YourBotPassword'
API_ENDPOINT = "https://en.wikipedia.org/w/api.php"
# Step 1: Get a login token
params = {
'action': 'query',
'meta': 'tokens',
'type': 'login',
'format': 'json'
}
s = requests.Session()
r = s.get(API_ENDPOINT, params=params)
data = r.json()
login_token = data['query']['tokens']['logintoken']
# Step 2: Log in using the bot password
login_params = {
'action': 'login',
'lgname': BOT_USERNAME,
'lgpassword': BOT_PASSWORD,
'lgtoken': login_token,
'format': 'json'
}
r = s.post(API_ENDPOINT, data=login_params)
login_data = r.json()
if login_data['login']['result'] == 'Success':
print(f"Successfully logged in as {BOT_USERNAME}")
# Step 3: Get a CSRF token for editing actions
params = {
'action': 'query',
'meta': 'tokens',
'format': 'json'
}
r = s.get(API_ENDPOINT, params=params)
data = r.json()
csrf_token = data['query']['tokens']['csrftoken']
# Step 4: Perform an authenticated action (e.g., edit a page)
edit_params = {
'action': 'edit',
'title': 'Sandbox',
'text': 'Hello from my bot! Current timestamp: ' + requests.utils.default_headers['User-Agent'],
'summary': 'Test edit via bot password',
'token': csrf_token,
'format': 'json'
}
r = s.post(API_ENDPOINT, data=edit_params)
edit_data = r.json()
if 'edit' in edit_data and edit_data['edit']['result'] == 'Success':
print(f"Successfully edited page: {edit_data['edit']['title']}")
else:
print("Edit failed:", edit_data)
else:
print("Login failed:", login_data)
This example demonstrates the multi-step process for bot password authentication, involving obtaining a login token, performing the login, and then acquiring a CSRF token for subsequent write operations. Always consult the MediaWiki API documentation for the most current and detailed instructions.
Security best practices
When integrating with the Wikipedia API and handling authentication, adherence to security best practices is crucial to protect user accounts and maintain the integrity of Wikipedia's content.
- Use OAuth 2.0 for user-facing applications: Whenever possible, opt for OAuth 2.0 to avoid direct handling of user credentials. This delegates authentication to Wikipedia, minimizing your application's security responsibilities and risk exposure. OAuth tokens should be stored securely and refreshed as needed, following the OAuth 2.0 specification.
- Employ bot passwords for automated scripts: For bots and automated tasks, bot passwords are more secure than using your main account password. They offer granular permissions and can be revoked individually without compromising your primary account.
- Store credentials securely: Never hardcode API keys, client 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 sensitive information.
- Restrict permissions (least privilege): When setting up bot passwords or OAuth scopes, grant only the minimum necessary permissions for your application to function. For example, if your bot only reads data, do not grant it editing permissions.
- Implement secure communication (HTTPS): Always use HTTPS for all API requests to encrypt data in transit, preventing eavesdropping and man-in-the-middle attacks. The MediaWiki API enforces HTTPS by default.
- Handle tokens and sessions carefully: OAuth access tokens and session cookies should have appropriate expiration times. Implement token refresh mechanisms for OAuth and secure session management for cookie-based authentication to prevent unauthorized access.
- Rate limit your requests: While not strictly an authentication best practice, respecting Wikipedia's API etiquette and rate limits helps maintain service availability and prevents your application from being blocked, which could impact your authenticated sessions.
- Regularly review and revoke unused credentials: Periodically audit your registered OAuth applications and bot passwords. Revoke any credentials that are no longer in use or if you suspect they have been compromised.