身份验证是将传入请求与一组识别凭证(例如请求的用户或其签名的令牌)相关联的机制。然后,权限和限制策略可以使用这些凭据来确定请求是否应该被允许。
认证 | 说明 |
---|---|
BasicAuthentication | 根据用户的用户名和密码进行签名。Basic Authentication 通常只适用于测试 |
TokenAuthentication | 简单的基于令牌的 HTTP 认证方案。令牌身份验证适用于 client-server 架构 |
RemoteUserAuthentication | 允许您将身份验证委托给您的 Web 服务器,该服务器设置 REMOTE_USER 环境变量 |
SessionAuthentication | session 后端进行认证。Session 身份验证适用于与您的网站在同一会话环境中运行的 AJAX 客户端** |
TokenAuthentication令牌验证
settings.py中
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
确保在更改设置后运行 manage.py migrate 。 rest_framework.authtoken 应用程序提供 Django 数据库迁移。
自己创建令牌
from rest_framework.authtoken.models import Token
users=UserPfile.objects.all()[0]
token = Token.objects.create(user=users) 接受为对象
print(token.key)
REST framework 提供了一个内置的视图放入urls中
urls.py中,用于创建Token
from rest_framework.authtoken import views
path('api-token-auth/', views.obtain_auth_token), 访问产生Token
path('api-token-auth/',ExampleView.as_view()),设置权限和认证
api/view.py中
Token限制访问
from rest_framework.authentication import BasicAuthentication,TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class ExampleView(APIView):
# 认证方式
authentication_classes = (TokenAuthentication, BasicAuthentication,)
# 认证权限
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
servers = Server.objects.all()
# servers_json=serializers(servers,)
content = serializers.serialize('json', servers)
return Response(content)
访问
在浏览器中输入http://10.0.122.156:100/api/jwt-token-auth/ 生成Token
输入Token,完成验证(GET方法)
image.png
网友评论