Django JWT身份验证

6 篇文章 0 订阅
1 篇文章 0 订阅

0X00 安装及基础使用

Django JWT是基于Django的auth模块和user model的,所以如果不使用Django的model那么是无法使用Django JWT的。其视图的实现方法是基于Django restframework的APIView和serializers。修正一下,准确的来说Django restframework JWT默认是基于auth模块和user model的,如果你对源码足够熟悉,将各个模块重写,那么将JWT结合到你自己的认证系统也是没有任何问题,不过使用自己的认证系统的话完全可以使用Token模块自己生成Token了,这种情况下使用JWT有点多此一举了。

废话讲到这里,正文开始

1.使用pip安装

pip install djangorestframework-jwt

2.在你的settings.py,添加JSONWebTokenAuthentication到Django REST框架DEFAULT_AUTHENTICATION_CLASSES

SessionAuthentication和BasicAuthentication在使用restframework的调试界面需要用到的模块。

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

3.urls.py

from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token

urlpatterns = [
    url(r'^login/', obtain_jwt_token), # 用于获取token
    url(r'^token-verify/', verify_jwt_token), # 验证令牌是否合法
    path(r'api-auth/', include('rest_framework.urls')), # 为restframework调试页面也开启验证
]

(1)obtain_jwt_token:提交用户名和密码,后台判定是否合法,合法的话返回一个Token,否则认证失败

- URL:/login/
- Request:
    - 请求方法:POST(表单)
    - 请求参数:username:'',password:''
Response:
    - 200,登录成功,返回{"token":"xxxxxx"}
    - 400,身份验证未通过

(2)verify_jwt_token:提交一个Token,后台判定Token是否过期

- URL:/token-verify/
- Request:
    - 请求方法:POST(application/json)
    - 请求参数:{"token":"xxxx"}
Response:
    - 200,验证通过,Token合法
    - 400,Token不合法或已过期

4.携带token请求接口

Token需要添加到HTTP请求头中,见下图

Key:Authorization
Value:JWT xxxxxxx

 

0X01 扩展Django User Model并与Django JWT结合

大概率会出现Django默认User Model字段不够用的情况,那么就需要继承User模块并添加字段。

添加一个APP用于新的User model

python manage.py startapp user_auth

1.models.py

User也是直接继承于AbsractUser的,所以我们直接继承该model并添加字段即可。

from django.contrib.auth.models import AbstractUser
from django.db import models

class UserInfo(AbstractUser):
    choice = (
        (1, 'admin'),
        (2, 'user')
    )
    user_type = models.IntegerField(choices=choice)

2.settings.py

修改Django Auth模块指向的model,改为我们重写后的model

AUTH_USER_MODEL = "user_auth.UserInfo"  # 重写user model后将用户认证指向重写后的model

3.保存更改

python manage.py makemigrations
python manage.py migrate

4.使用ModelViewSet和ModelSerializer

class UserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        instance = UserInfo.objects.create_user(**validated_data)
        return instance

    def update(self, instance, validated_data):
        """
        只允许更新password字段
        :param instance:
        :param validated_data:
        :return:
        """
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    class Meta:
        model = UserInfo
        fields = ('id', 'username', 'user_type', 'date_joined', 'password')
        read_only_fields = ['date_joined']
        extra_kwargs = {'password': {'write_only': True}}

class UserViewSet(ModelViewSet):
    permission_classes = (UserReadAdminWrite,)
    queryset = UserInfo.objects.all()
    serializer_class = UserSerializer

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if request.user.id == instance.id:
            return Response({'ERROR': '不能删除正在使用的用户'} ,status=status.HTTP_403_FORBIDDEN)
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

JWT更多设置参数及用法见 http://getblimp.github.io/django-rest-framework-jwt/

0X02 

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        #   设置访问权限为只读
        # 'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        #   设置访问权限为必须登录
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        #  使用rest_framework的界面需要下列认证模块
        #'rest_framework.authentication.SessionAuthentication',
        #'rest_framework.authentication.BasicAuthentication',
    ),
}

如果加载了sessionAuthentication和BasicAuthentication模块,那么通过了JWT身份认证后,会设置一个cookide,session_id=xxx,使用该session_id,不使用Token也可以正常访问后台接口,如果只允许Token验证,需要注释掉session模块和basic模块。

源码:

Authentication类都必须继承于BaseAuthentication类:

class BaseAuthentication(object):
    """
    All authentication classes should extend BaseAuthentication.
    """

    def authenticate(self, request):
        """
        Authenticate the request and return a two-tuple of (user, token).
        """
        raise NotImplementedError(".authenticate() must be overridden.")

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        pass

 

定义的Authentication类会在调用视图函数之前被调用:

class APIView(View):

    # The following policies may be set at either globally, or per-view.
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES # !!!#
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS

    # Allow dependency injection of other settings to make testing easier.
    settings = api_settings

    schema = DefaultSchema()

 

dispatch方法应该是用于处理所有请求,dispatch函数:

    def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs) # 该方法尤为重要,如下

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
    def initial(self, request, *args, **kwargs):
        """
        运行所有在视图函数前应该被调用的东西
        """
        self.format_kwarg = self.get_format_suffix(**kwargs)

        # Perform content negotiation and store the accepted info on the request
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg

        # Determine the API version, if versioning is in use.
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        self.perform_authentication(request) # 用户认证
        self.check_permissions(request) # 权限认证
        self.check_throttles(request) # 访问频率限制

用户认证的具体方法:

perform_authentication:该函数只有一个request.user属性,利用了property的特性,通过属性转换为方法。

    def perform_authentication(self, request):
        """
        Perform authentication on the incoming request.

        Note that if you override this and simply 'pass', then authentication
        will instead be performed lazily, the first time either
        `request.user` or `request.auth` is accessed.
        """
        request.user

调用的具体方法:

request.py的Request类的方法:

    @property
    def user(self):
        """
        Returns the user associated with the current request, as authenticated
        by the authentication classes provided to the request.
        """
        if not hasattr(self, '_user'):
            with wrap_attributeerrors():
                self._authenticate()  # 调用所有认证方法
        return self._user

_authenticate方法:遍历加载的所有authentication方法并认证,如果认证通过就添加request.user属性

    def _authenticate(self):
        """
        Attempt to authenticate the request using each authentication instance
        in turn.
        """
        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated()

0X03 关于JWT的认证逻辑

1.登录,对应的是obtain_jwt_token这个视图,上面说过登录成功会返回一个Token

from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path(r'login/', obtain_jwt_token),
]

在该视图使用的序列化器(JsonWebTokenSerializer)中,验证用户名密码的方法如下:

    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)

进一步查看autenticate(**credentials)方法:

def authenticate(request=None, **credentials):
    """
    If the given credentials are valid, return a User object.
    """
    for backend, backend_path in _get_backends(return_tuples=True):
        try:
            inspect.getcallargs(backend.authenticate, request, **credentials)
        except TypeError:
            # This backend doesn't accept these credentials as arguments. Try the next one.
            continue
        try:
            user = backend.authenticate(request, **credentials)
        except PermissionDenied:
            # This backend says to stop in our tracks - this user should not be allowed in at all.
            break
        if user is None:
            continue
        # Annotate the user object with the path of the backend.
        user.backend = backend_path
        return user

这个认证利用的是Django的AUTHENTICATION_BACKENDS,_get_backends方法会获取所有注册的认证后台:

def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backend = load_backend(backend_path)
        backends.append((backend, backend_path) if return_tuples else backend)
    if not backends:
        raise ImproperlyConfigured(
            'No authentication backends have been defined. Does '
            'AUTHENTICATION_BACKENDS contain anything?'
        )
    return backends

当调用 django.contrib.auth.authenticate() 方法时,Django将获取注册的所有认证后台,然后按顺序进行调用,直到某个认证后台认证成功,成功返回User对象,成功返回User对象后不会再进行后续的认证。认证后台的设置在settings.py中,默认没有该字段,但是具有默认值,默认值为(‘django.contrib.auth.backends.ModelBackend’,),使用Django默认的用户认证进行认证。

2.登录成功后将获取到的Token携带到HTTP请求头中,即可完成验证,下面说下后台对Token的验证机制。

验证机制其实非常简单,就是对Token进行反序列化,获取Token中存取的username和过期时间,如果无法解析或用户名不存在或已过期,都会造成认证失败。

    def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)

        return (user, jwt_value)

3.

用户可以自行编写认证后台。在settings.py中添加:

AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) # 此为默认配置

用户自己的认证后台直接继承rest_framework authentication.py中的BaseAuthentication,然后按照要求编写即可。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值