在Web开发中,认证是确保用户身份合法性的关键环节。Python提供了多种实现认证的方式,其中Basic Auth和Token认证是两种常见方案。
Basic Auth实现****
Basic Auth是一种简单的HTTP认证机制,通过将用户名和密码以Base64编码形式包含在请求头中实现认证。
python
| from flask import Flask, request, make_response | |
|---|---|
| import base64 | |
| app = Flask(name) | |
| VALID_CREDENTIALS = {'admin': 'password123'} | |
| @app.route('/protected') | |
| def protected(): | |
| auth_header = request.headers.get('Authorization') | |
| if not auth_header: | |
| return unauthorized_response() | |
| try: | |
| auth_type, auth_string = auth_header.split(' ', 1) | |
| if auth_type.lower() != 'basic': | |
| return unauthorized_response() | |
| decoded_bytes = base64.b64decode(auth_string) | |
| username, password = decoded_bytes.decode().split(':', 1) | |
| if username in VALID_CREDENTIALS and VALID_CREDENTIALS[username] == password: | |
| return "Access granted to protected resource" | |
| return unauthorized_response() | |
| except: | |
| return unauthorized_response() | |
| def unauthorized_response(): | |
| response = make_response("Unauthorized", 401) | |
| response.headers['WWW-Authenticate'] = 'Basic realm="Secure Area"' | |
| return response |
Basic Auth实现简单但安全性较低;Token认证更安全灵活,适合现代Web应用。实际开发中应根据安全需求选择合适方案。