drf jwt 认证

作者: 程序员同行者 | 来源:发表于2018-07-23 14:26 被阅读5次
    JWT是什么(Json Web Token)

    JWT 是一个开放标准(RFC 7519),它定义了一种用于简洁,自包含的用于通信双方之间以 JSON 对象的形式安全传递信息的方法。JWT 可以使用 HMAC 算法或者是 RSA 的公钥密钥对进行签名。它具备两个特点:

    简洁(Compact)

    • 可以通过URL, POST 参数或者在 HTTP header 发送,因为数据量小,传输速度快

    自包含(Self-contained)

    • 负载中包含了所有用户所需要的信息,避免了多次查询数据库

    这篇文章https://www.jianshu.com/p/180a870a308a原理讲的很清楚。

    我这就不讲过多原理,直接讲如何使用

    安装JWT
    # settings.py
    (python36env) [vagrant@localhost ~]$ pip install djangorestframework-jwt
    Looking in indexes: http://pypi.douban.com/simple
    Collecting djangorestframework-jwt
      Downloading http://pypi.doubanio.com/packages/2b/cf/b3932ad3261d6332284152a00c3e3a275a653692d318acc6b2e9cf6a1ce3/djangorestframework_jwt-1.11.0-py2.py3-none-any.whl
    Collecting PyJWT<2.0.0,>=1.5.2 (from djangorestframework-jwt)
      Downloading http://pypi.doubanio.com/packages/93/d1/3378cc8184a6524dc92993090ee8b4c03847c567e298305d6cf86987e005/PyJWT-1.6.4-py2.py3-none-any.whl
    Installing collected packages: PyJWT, djangorestframework-jwt
    Successfully installed PyJWT-1.6.4 djangorestframework-jwt-1.11.0
    
    修改settings.py文件
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'rest_framework.authtoken',  # 设置token
        ...
    ]
    REST_FRAMEWORK = {
        ...
        # 添加JWT全局认证
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    
        ),
        }
    # 自定义token过期时间
    import datetime
    JWT_AUTH = {
        'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=86400),
    }
    # 还有很多其他相关设置,可以查阅相关文档
    
    
    修改序列化文件
    # serializers.py
    from  rest_framework import serializers
    from  django.contrib.auth.models import  Group
    class UserGroupsSerializer(serializers.ModelSerializer):
        """
        用户组序列化类
        """
        class Meta:
            model = Group
            fields = "__all__"
    

    修改视图文件

    # views.py
    from  django.contrib.auth.models import Group
    from rest_framework.permissions import IsAuthenticated
    from  .serializers import UserGroupsSerializer
    
    class UserGropInfoViewset(viewsets.ModelViewSet):
        permission_classes = (IsAuthenticated,)
        queryset = Group.objects.all()
        serializer_class = UserGroupsSerializer
    
    
    修改路由文件
    # 当前app下的router.py
    from  rest_framework.routers import DefaultRouter
    from  .views import UserGropInfoViewset
    group_router = DefaultRouter()
    
    group_router.register('GroupsInfo',UserGropInfoViewset,base_name='GroupsInfo')
    
    # 全局url.py
    from  rest_framework.routers import DefaultRouter
    route = DefaultRouter()
    from users.router import group_router
    route.registry.extend(group_router.registry)
    
    # 配置jwt路由
    from rest_framework_jwt.views import obtain_jwt_token
    urlpatterns = [
        url(r'^', include(route.urls)),
        url(r'^api-auth',include('rest_framework.urls',namespace='rest_framework')),
        # 使用jwt验证
        url(r'^api-token-auth/', obtain_jwt_token),
    
    测试
    # 获取JWT token
    (python36env) [vagrant@localhost ~]$  curl -X POST -d "username=admin&password=123456" http://localhost:8000/api-tok
    en-auth/
    {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTMyMjI2NDYwLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSJ9.Ow9qZQ8AszS0RnY7ZU6F-AKmUDgBet9uLgmYbWYTJzo"}
    
    # 使用token 获取数据
    (python36env) [vagrant@localhost ~]$  curl -H "Authorization: JWT  eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo
    yLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTMyMjI2NDYwLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSJ9.Ow9qZQ8AszS0RnY7ZU6F-AKmUDgBet9uL
    gmYbWYTJzo"  http://localhost:8000/users/  | python -m json.tool
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   666  100   666    0     0   8983      0 --:--:-- --:--:-- --:--:--  9123
    {
        "count": 79,
        "next": "http://localhost:8000/users/?page=2",
        "previous": null,
        "results": [
            {
                "id": 1,
                "username": "eric",
                "email": ""
            },
            {
                "id": 2,
                "username": "admin",
                "email": "admin@admin.com"
            },
            {
                "id": 3,
                "username": "panda-1",
                "email": "panda-1@qq.com"
            },
            {
                "id": 4,
                "username": "panda-2",
                "email": "panda-2@qq.com"
            },
            {
                "id": 5,
                "username": "panda-3",
                "email": "panda-3@qq.com"
            },
            {
                "id": 6,
                "username": "panda-4",
                "email": "panda-4@qq.com"
            },
            {
                "id": 7,
                "username": "panda-5",
                "email": "panda-5@qq.com"
            },
            {
                "id": 8,
                "username": "panda-6",
                "email": "panda-6@qq.com"
            },
            {
                "id": 9,
                "username": "panda-7",
                "email": "panda-7@qq.com"
            },
            {
                "id": 10,
                "username": "panda-8",
                "email": "panda-8@qq.com"
            }
        ]
        }
    

    相关文章

      网友评论

        本文标题:drf jwt 认证

        本文链接:https://www.haomeiwen.com/subject/rbqjmftx.html