Practical Session and Token Authentication with Python Requests
This article demonstrates practical implementations of session-based and token-based authentication, including JWT and a dual-token (access and refresh) mechanism, using Python's requests library, and explains how to obtain, use, and refresh tokens for protected API endpoints in automated testing.
1. Session Authentication Practice
Session authentication is a traditional method where the server creates a session after user login and returns a Session ID via a cookie; subsequent requests include this cookie to maintain the login state.
1.1 Obtain Session
import requests
def login_with_session():
url = "https://api.example.com/login"
data = {
"username": "user1",
"password": "pass1",
}
session = requests.Session()
response = session.post(url, data=data)
assert response.status_code == 200, "登录失败"
return session
def test_protected_resource_with_session():
session = login_with_session()
url = "https://api.example.com/protected"
response = session.get(url)
assert response.status_code == 200, "访问受保护资源失败"
print("访问成功,响应内容:", response.json())Explanation: Using requests.Session() creates a session object that automatically manages cookies, so after a successful login the Session ID is sent with every subsequent request.
2. Token Authentication Practice
Token authentication (e.g., JWT) is a modern, stateless approach where the client receives a token after login and includes it in the Authorization header of subsequent requests.
2.1 Obtain Token
import requests
def login_with_token():
url = "https://api.example.com/login"
data = {
"username": "user1",
"password": "pass1",
}
response = requests.post(url, json=data)
assert response.status_code == 200, "登录失败"
token = response.json().get("token")
return token
def test_protected_resource_with_token():
token = login_with_token()
url = "https://api.example.com/protected"
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.get(url, headers=headers)
assert response.status_code == 200, "访问受保护资源失败"
print("访问成功,响应内容:", response.json())Explanation: After a successful login the server returns a token, which the client places in the Authorization header for all subsequent API calls.
3. Dual‑Token Mechanism (AccessToken & RefreshToken)
In scenarios requiring enhanced security, a short‑lived AccessToken is used together with a RefreshToken that can obtain new AccessTokens when the former expires.
3.1 Obtain and Refresh Tokens
import requests
def login_with_refresh_token():
url = "https://api.example.com/login"
data = {
"username": "user1",
"password": "pass1",
}
response = requests.post(url, json=data)
assert response.status_code == 200, "登录失败"
tokens = response.json()
return tokens["accessToken"], tokens["refreshToken"]
def refresh_token(refresh_token):
url = "https://api.example.com/refresh"
headers = {
"Authorization": f"Bearer {refresh_token}"
}
response = requests.post(url, headers=headers)
assert response.status_code == 200, "刷新 Token 失败"
return response.json().get("accessToken")
def test_protected_resource_with_refresh_token():
access_token, refresh_token = login_with_refresh_token()
print("初始 Access Token:", access_token)
# Simulate AccessToken expiration and refresh it
new_access_token = refresh_token(refresh_token)
print("刷新后的 Access Token:", new_access_token)
# Use the new AccessToken to access the protected resource
url = "https://api.example.com/protected"
headers = {
"Authorization": f"Bearer {new_access_token}"
}
response = requests.get(url, headers=headers)
assert response.status_code == 200, "访问受保护资源失败"
print("访问成功,响应内容:", response.json())Explanation: The login function returns both an AccessToken and a RefreshToken; when the AccessToken expires, the RefreshToken is sent to a refresh endpoint to obtain a new AccessToken, which is then used for subsequent protected requests.
4. Summary
In API automated testing, Session and Token authentication are two common login methods. Session authentication suits traditional web applications, while Token authentication (such as JWT) fits stateless API architectures. The dual‑token mechanism further enhances security for applications that require long‑lived sessions.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.