Of course! Here’s a comprehensive guide on how to implement Baidu OAuth 2.0 authentication in Python.

We will cover:
- Prerequisites: What you need from the Baidu AI Platform.
- Core Concepts: Understanding the OAuth 2.0 "Authorization Code Grant" flow, which is the most common and secure method.
- Step-by-Step Python Implementation: Using the popular
requestslibrary to make the necessary API calls. - Complete Code Example: A runnable script that you can adapt.
- Important Security Note: Storing your client secret securely.
Prerequisites: Get Your API Key and Secret Key
Before you start, you need to register your application on the Baidu AI Platform to get your credentials.
- Go to the Baidu AI Open Platform: https://ai.baidu.com/tech
- Log in with your Baidu account.
- Navigate to "Console" -> "AI Studio" -> "Application Management".
- Click "Create Application".
- Fill in the application details:
- Application Name: A name for your app (e.g., "My Python OAuth App").
- Application Type: Choose "Server-side application" (Web application). This is crucial as it allows you to use the Authorization Code flow and securely store your
client_secret. - Authorization callback URL: This is the URL in your application that Baidu will redirect the user to after they grant permission. For local development and testing, you can use a placeholder like
http://localhost:8000/auth/callback. You must register this URL in your Baidu console settings.
- After creating the application, you will be given a API Key (Client ID) and a Secret Key (Client Secret). Treat your Secret Key like a password and never expose it in client-side code (e.g., in a JavaScript file or a public GitHub repository).
Core Concepts: The OAuth 2.0 Authorization Code Flow
We will use the Authorization Code Grant flow, which involves these main steps:
- Authorization Request: Your application redirects the user to Baidu's authorization endpoint with your
client_id, theredirect_uri, and the desiredscope(permissions). - User Consent: The user logs in to Baidu (if they aren't already) and sees a screen asking if they want to grant your application permission to access their data. They click "Authorize".
- Redirect with Authorization Code: Baidu redirects the user back to your
redirect_uri, but this time it includes a temporary, single-usecodein the URL parameters. - Token Request: Your server-side Python application takes this
code, along with yourclient_idandclient_secret, and sends a direct, server-to-server request to Baidu's token endpoint to exchange thecodefor anaccess_token. - Receive Access Token: If the
codeis valid, Baidu responds with anaccess_token. This token is what you use to make authenticated API calls on behalf of the user.
Step-by-Step Python Implementation
We'll use the requests library. If you don't have it, install it:

pip install requests
Let's define the necessary constants first. Replace the placeholder values with your actual credentials.
import requests import json # --- Configuration --- # Replace with your actual Baidu API credentials CLIENT_ID = 'YOUR_API_KEY' # Your API Key (Client ID) CLIENT_SECRET = 'YOUR_SECRET_KEY' # Your Secret Key (Client Secret) REDIRECT_URI = 'http://localhost:8000/auth/callback' # Must match the one in your Baidu console # Baidu OAuth endpoints AUTHORIZATION_URL = 'https://openapi.baidu.com/oauth/2.0/authorize' TOKEN_URL = 'https://openapi.baidu.com/oauth/2.0/token'
Step 1: Generate the Authorization URL
This is the URL you will redirect the user to. You can construct it manually or use urllib.parse to build it safely.
from urllib.parse import urlencode, quote
def get_baidu_auth_url():
"""Constructs the Baidu OAuth authorization URL."""
params = {
'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'scope': 'basic netdisk', # Example scope: basic info and Baidu Netdisk API access
'display': 'page' # or 'popup'
}
# The state parameter is highly recommended for security to prevent CSRF attacks
params['state'] = 'YOUR_RANDOM_STRING_OR_HASH'
return f"{AUTHORIZATION_URL}?{urlencode(params)}"
# Example usage:
# print("Please visit this URL to authorize:", get_baidu_auth_url())
Step 2: Exchange the Authorization Code for an Access Token
After the user grants permission, Baidu will redirect them to your REDIRECT_URI with a code in the query string (e.g., http://localhost:8000/auth/callback?code=THE_AUTH_CODE&state=YOUR_RANDOM_STRING).
Your Python code (running on your server) will need to capture this code and use it to get the token.

def get_access_token(auth_code):
"""Exchanges an authorization code for an access token."""
data = {
'grant_type': 'authorization_code',
'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI
}
try:
response = requests.post(TOKEN_URL, data=data)
response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
token_data = response.json()
if 'access_token' in token_data:
print("Successfully obtained access token!")
# print(json.dumps(token_data, indent=2))
return token_data
else:
print("Error obtaining token:", token_data.get('error_description', 'Unknown error'))
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred during the token request: {e}")
return None
# Example usage (you would get 'auth_code' from your web framework's request handler):
# auth_code_from_redirect = "THE_CODE_FROM_BAIDU_URL"
# token_info = get_access_token(auth_code_from_redirect)
# if token_info:
# access_token = token_info['access_token']
Complete Runnable Example (Simulated)
This example simulates the flow. In a real web application (using Flask, Django, etc.), you would have a route for the redirect callback.
import requests
import json
from urllib.parse import urlencode
# --- Configuration ---
CLIENT_ID = 'YOUR_API_KEY'
CLIENT_SECRET = 'YOUR_SECRET_KEY'
REDIRECT_URI = 'http://localhost:8000/auth/callback'
AUTHORIZATION_URL = 'https://openapi.baidu.com/oauth/2.0/authorize'
TOKEN_URL = 'https://openapi.baidu.com/oauth/2.0/token'
def get_baidu_auth_url():
"""Constructs the Baidu OAuth authorization URL."""
params = {
'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'scope': 'basic netdisk',
'state': 'a_very_random_state_string_12345' # IMPORTANT: Use a real random string
}
return f"{AUTHORIZATION_URL}?{urlencode(params)}"
def get_access_token(auth_code):
"""Exchanges an authorization code for an access token."""
print("\n--- Exchanging Code for Token ---")
data = {
'grant_type': 'authorization_code',
'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI
}
try:
response = requests.post(TOKEN_URL, data=data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
def make_api_call(access_token):
"""Makes an authenticated API call to get user info."""
print("\n--- Making Authenticated API Call ---")
# Example API: Get current user's Baidu ID
user_info_url = "https://openapi.baidu.com/rest/2.0/passport/users/getinfo"
params = {
'access_token': access_token,
'fields': 'userid,username,realname'
}
try:
response = requests.get(user_info_url, params=params)
response.raise_for_status()
user_data = response.json()
print("User Info API Response:")
print(json.dumps(user_data, indent=2))
return user_data
except requests.exceptions.RequestException as e:
print(f"An error occurred during the API call: {e}")
return None
if __name__ == '__main__':
# 1. Get the authorization URL
auth_url = get_baidu_auth_url()
print("Step 1: Authorization URL generated.")
print(f"Please visit this URL in your browser to authorize the application:\n{auth_url}")
# 2. Simulate the user being redirected back and getting the code
# In a real app, you'd parse this from your web server's request
input("After authorizing, copy the 'code' from the redirect URL (e.g., http://localhost:8000/auth/callback?code=...) and paste it here, then press Enter: ")
# For this simulation, let's pretend the code is pasted here.
# You would manually get this from the URL after redirecting.
# Example: auth_code_pasted = "4.Z......"
auth_code_pasted = input("Paste the code here: ")
if not auth_code_pasted or not auth_code_pasted.startswith("4."):
print("Invalid code format. Exiting.")
else:
# 3. Exchange the code for an access token
token_info = get_access_token(auth_code_pasted)
if token_info and 'access_token' in token_info:
access_token = token_info['access_token']
# 4. Use the access token to call a protected API
user_info = make_api_call(access_token)
if user_info and 'userid' in user_info:
print(f"\nSuccessfully logged in as: {user_info.get('username', 'N/A')} (ID: {user_info.get('userid')})")
Important Security Note: Storing Your client_secret
NEVER hardcode your CLIENT_SECRET directly in your source code if you plan to commit it to a version control system like Git.
Instead, use environment variables. This is the standard and most secure practice.
How to do it:
-
Install a library:
python-dotenvmakes managing environment variables from a.envfile easy.pip install python-dotenv
-
Create a
.envfile in your project root:# .env file BAIDU_CLIENT_ID="YOUR_API_KEY" BAIDU_CLIENT_SECRET="YOUR_SECRET_KEY" BAIDU_REDIRECT_URI="http://localhost:8000/auth/callback" -
Update your Python code to load variables from the
.envfile:import os from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Now you can access them securely CLIENT_ID = os.getenv("BAIDU_CLIENT_ID") CLIENT_SECRET = os.getenv("BAIDU_CLIENT_SECRET") REDIRECT_URI = os.getenv("BAIDU_REDIRECT_URI") # Make sure to add .env to your .gitignore file! # .gitignore # ... # .env
This way, your sensitive credentials are kept out of your repository and can be easily configured for different environments (development, production).
