import os from django.conf import settings def set_auth_cookies(response, access_token=None, refresh_token=None): """ 为响应设置 HttpOnly Cookie(杜绝 XSS 窃取 token) - access_token: HttpOnly, SameSite=Lax, Path=/ - refresh_token: HttpOnly, SameSite=Lax, Path=/ 在生产/非 DEBUG 开启 Secure,本地开发/内网环境保持 Secure=False。 """ if not response: return response debug_mode = getattr(settings, 'DJANGO_DEBUG', settings.DEBUG) if isinstance(debug_mode, str): debug_mode = debug_mode.lower() in ('true', '1', 'yes') secure = not debug_mode samesite = 'Lax' jwt_settings = getattr(settings, 'SIMPLE_JWT', {}) if access_token: access_lifetime = jwt_settings.get('ACCESS_TOKEN_LIFETIME') max_age = int(access_lifetime.total_seconds()) if access_lifetime else 7 * 86400 response.set_cookie( key='access_token', value=str(access_token), max_age=max_age, httponly=True, samesite=samesite, secure=secure, path='/' ) if refresh_token: refresh_lifetime = jwt_settings.get('REFRESH_TOKEN_LIFETIME') max_age = int(refresh_lifetime.total_seconds()) if refresh_lifetime else 30 * 86400 response.set_cookie( key='refresh_token', value=str(refresh_token), max_age=max_age, httponly=True, samesite=samesite, secure=secure, path='/' ) return response def clear_auth_cookies(response): """ 清除认证 HttpOnly Cookie """ if not response: return response response.delete_cookie('access_token', path='/') response.delete_cookie('refresh_token', path='/') return response