如何在Django REST Framework函数视图中应用自定义认证类?
在Django REST Framework函数视图中使用自定义认证类
要在DRF的函数视图中使用你定义的CustomAuthentication,只需按以下步骤操作:
- 导入自定义认证类:从你存放该类的模块中导入(比如类在
your_app.authentication.py里,就用对应的导入路径) - 给函数视图添加装饰器:将自定义认证类传入
@authentication_classes装饰器的列表参数中,可单独使用,也可和其他认证类搭配。
完整代码示例:
from rest_framework.decorators import authentication_classes from your_app.authentication import CustomAuthentication # 替换为实际导入路径 @authentication_classes([CustomAuthentication]) def your_target_view(request): # 编写你的视图业务逻辑 pass
额外提示
你当前的CustomAuthentication类仅调用了父类的authenticate方法,而BaseAuthentication的默认实现会直接抛出NotAuthenticated异常。实际项目中需要重写authenticate方法,实现专属的认证逻辑,比如从请求头校验token:
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed class CustomAuthentication(BaseAuthentication): def authenticate(self, request): # 示例:从请求头获取认证token token = request.headers.get('Authorization') if not token: raise AuthenticationFailed("未提供认证凭证") # 此处添加token有效性校验逻辑,比如查询数据库匹配用户 user = self.validate_token(token) if not user: raise AuthenticationFailed("无效的认证凭证") # 验证通过后返回(user, auth)元组 return (user, token)
内容的提问来源于stack exchange,提问作者Abhijee Pandey
相关产品推荐
相关产品推荐

