curl --request POST \
--url https://api.example.com/api/token/refresh/ \
--header 'Content-Type: application/json' \
--data '
{
"refresh": "<string>"
}
'{
"access": "<string>",
"refresh": "<string>"
}Obtain a new access token using a refresh token
curl --request POST \
--url https://api.example.com/api/token/refresh/ \
--header 'Content-Type: application/json' \
--data '
{
"refresh": "<string>"
}
'{
"access": "<string>",
"refresh": "<string>"
}Documentation Index
Fetch the complete documentation index at: https://mintlify.com/edimez14/password_generator/llms.txt
Use this file to discover all available pages before exploring further.
POST /api/token/refresh/
curl -X POST http://localhost:8000/api/token/refresh/ \
-H "Content-Type: application/json" \
-d '{
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}'
import requests
url = "http://localhost:8000/api/token/refresh/"
payload = {
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}
response = requests.post(url, json=payload)
data = response.json()
# Update stored access token
new_access_token = data['access']
const refreshToken = localStorage.getItem('refresh_token');
fetch('http://localhost:8000/api/token/refresh/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
refresh: refreshToken
})
})
.then(response => response.json())
.then(data => {
// Update the access token
localStorage.setItem('access_token', data.access);
});
{
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQ2MjQ3NjAwLCJpYXQiOjE2NDYyNDQwMDAsImp0aSI6IjE5MmVkNDMyOGViYTQxNzM5NGU1ZjU5ZDI5MzA5ZDYxIiwidXNlcl9pZCI6MX0.hHx4L-lPl9VQfq7FzhwXKvzGiJlMZ4xDkLv7nF5Y6Yw"
}
{
"detail": "Token is invalid or expired",
"code": "token_not_valid"
}
{
"detail": "Token is blacklisted",
"code": "token_not_valid"
}
{
"refresh": ["This field is required."]
}
backend/urls.py:16:
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
# ... other paths
]
Authorization: Bearer <access_token>
/api/token/refresh/ with the refresh tokenimport axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000/api'
});
// Add access token to requests
api.interceptors.request.use(
config => {
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// Refresh token on 401 errors
api.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const refreshToken = localStorage.getItem('refresh_token');
const response = await axios.post(
'http://localhost:8000/api/token/refresh/',
{ refresh: refreshToken }
);
const { access } = response.data;
localStorage.setItem('access_token', access);
// Retry original request with new token
originalRequest.headers.Authorization = `Bearer ${access}`;
return api(originalRequest);
} catch (refreshError) {
// Refresh token is invalid, redirect to login
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
window.location.href = '/login';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
export default api;
import requests
from typing import Dict, Optional
class APIClient:
def __init__(self, base_url: str):
self.base_url = base_url
self.access_token: Optional[str] = None
self.refresh_token: Optional[str] = None
def _refresh_access_token(self) -> bool:
"""Refresh the access token using the refresh token."""
if not self.refresh_token:
return False
try:
response = requests.post(
f"{self.base_url}/token/refresh/",
json={"refresh": self.refresh_token}
)
response.raise_for_status()
self.access_token = response.json()['access']
return True
except requests.exceptions.RequestException:
return False
def request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
"""Make an authenticated request with automatic token refresh."""
headers = kwargs.pop('headers', {})
if self.access_token:
headers['Authorization'] = f'Bearer {self.access_token}'
response = requests.request(
method,
f"{self.base_url}{endpoint}",
headers=headers,
**kwargs
)
# If unauthorized, try refreshing token and retry
if response.status_code == 401 and self._refresh_access_token():
headers['Authorization'] = f'Bearer {self.access_token}'
response = requests.request(
method,
f"{self.base_url}{endpoint}",
headers=headers,
**kwargs
)
return response
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}
rest_framework_simplejwt.views.TokenRefreshView