test development python django-61. certification authority (permission)

Foreword

After the user logs on, only the current user's operating authority, the user can not operate other people, this is the need to use the certification authority, or else you log in to your user, others to operate the user's data, it is dangerous.

  • authentication is authentication, to determine the current user's login authentication method which is
  • permissions is a certification authority to determine which users have permission to operate

authentication Authentication

Authentication is requested and will receive a set of identity credentials (such as user name and password, token) carried out a mechanism related to permissions and policies can decide whether to allow the request based on the identity certificate. Therefore, authentication occurs before the verification permissions and limit checking.

When a request is received by authentication:

  • request.user property is set to django.contrib.auth.User object, the object of our login (we define user inherited User).
  • request.auth is set corresponding to the Token (if with a Token) or None (if not with Token).
    When a request authentication failed:

  • request.user property is set to django.contrib.auth.models.AnonymousUser object.
  • request.auth is set to None.

django rest framework permission and certification in four ways:

  • BasicAuthentication this authentication scheme uses HTTP basic authentication, the user is signed in accordance with a user name and password. Basic authentication is usually only available for testing
  • TokenAuthentication this authentication scheme uses a simple HTTP-based token authentication scheme. It applies to both client authentication token - server settings, such as native desktop and mobile clients.
  • Use Django's default session backend SessionAuthentication this authentication scheme to authenticate. Session authentication applies to AJAX clients to your site is running in the same session context.
  • RemoteUserAuthentication This authentication scheme allows you to delegate authentication to the Web server, which set the REMOTE_USER environment variable.

permission certification authority

Permission checks usually request.user identity verification and request.auth attribute information to determine whether it should allow incoming requests.

When a permissions check fails, returns a HTTP 403 Forbidden or HTTP 401 Unauthorized according to the following rules:

  • If you receive a request authenticated, but authentication failed, HTTP returns 403 Forbidden;
  • If the received authentication request fails, and the highest priority classes can not be verified request WWW-Authenticate header, HTTP return 403 Forbidden;
  • If the received authentication request fails, and a highest priority class may be used to verify the request WWW-Authenticate header, HTTP 401 Unauthorized returned

Permission levels are also four

  • AllowAny allow all users
  • IsAuthenticated represent only allow authenticated users to access through, inaccessible to other users.
  • IsAdminUser represent only allows an administrator user access, ordinary users can not access.
  • IsAuthenticatedOrReadOnly represents only allows authenticated users to access, or only allows read-only request (GET request) to access.

Related

In settings.py in, INSTALLED_APPS add rest_framework and rest_framework.authtoken

INSTALLED_APPS = [
    'apiapp',
    'rest_framework.authtoken',
    'rest_framework',
]

REST_FRAMEWORK add permissions authentication and identity authentication

REST_FRAMEWORK = {
    # 权限认证
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',            # IsAuthenticated 仅通过认证的用户
        'rest_framework.permissions.AllowAny',                   # AllowAny 允许所有用户
        'rest_framework.permissions.IsAdminUser',                # IsAdminUser 仅管理员用户
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',  # IsAuthenticatedOrReadOnly 认证的用户可以完全操作,否则只能get读取
    ),
    # 身份认证
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',  # token认证
    )
}

Login generate token

Login time, does not require authentication, permission_classes set to AllowAny, allowing all users

permission_classes = (AllowAny,) # AllowAny allow all users

from django.http import JsonResponse
from django.shortcuts import HttpResponse
from rest_framework.authtoken.models import Token
from django.contrib import auth
from rest_framework.views import APIView
from rest_framework import viewsets
from rest_framework import serializers
from .models import *
from django.http import QueryDict
from rest_framework.request import Request
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.authentication import TokenAuthentication

'''作者:上海悠悠,QQ交流群:750815713'''

class LoginViewSet(APIView):
    '''登录获取token方法'''
    permission_classes = (AllowAny,)      # AllowAny 允许所有用户

    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        # print(username)
        password = request.data.get('password')
        user = auth.authenticate(username=username, password=password)
        if not user:
            return HttpResponse({"code": 0,
                                "msg": "用户名或密码不对!"})
        # 删除原有的Token
        old_token = Token.objects.filter(user=user)
        old_token.delete()
        # 创建新的Token
        token = Token.objects.create(user=user)
        return JsonResponse({"code": 0,
                             "msg": "login success!",
                             "username": user.username,
                             "token": token.key})

Add card information, and then speak in front of an add authentication_classes and permission_classes

authentication_classes = (TokenAuthentication,) # token authentication
permission_classes = (IsAuthenticated,) # # IsAuthenticated only authenticated users

def get_parameter_dic(request, *args, **kwargs):
    # 作者:上海悠悠,QQ交流群:750815713
    if isinstance(request, Request) == False:
        return {}

    query_params = request.query_params
    if isinstance(query_params, QueryDict):
        query_params = query_params.dict()
    result_data = request.data
    if isinstance(result_data, QueryDict):
        result_data = result_data.dict()

    if query_params != {}:
        return query_params
    else:
        return result_data


class CardSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Card
        fields = "__all__"

class CardViewSet(viewsets.ModelViewSet):
    '''# 作者:上海悠悠,QQ交流群:750815713'''
    authentication_classes = (TokenAuthentication,)   # token认证
    permission_classes = (IsAuthenticated,)  # # IsAuthenticated 仅通过认证的用户
    queryset = Card.objects.all()
    serializer_class = CardSerializer

    def get(self, request, *args, **kwargs):
        params=get_parameter_dic(request)
        return JsonResponse(data=params)

    def post(self, request, *args, **kwargs):
        params=get_parameter_dic(request)
        return JsonResponse(data=params)

    def put(self, request, *args, **kwargs):
        params=get_parameter_dic(request)
        return JsonResponse(data=params)

models.py design card table

class Card(models.Model):
    '''银行卡 基本信息 # 作者:上海悠悠,QQ交流群:750815713'''
    card_id = models.CharField(max_length=30, verbose_name="卡号", default="")
    card_user = models.CharField(max_length=10, verbose_name="姓名", default="")
    add_time = models.DateField(auto_now=True, verbose_name="添加时间")

    class Meta:
        verbose_name_plural = '银行卡账户'
        verbose_name = "银行卡账户_基本信息"
        
    def __str__(self):
        return self.card_id

Add Method Address urls.py

from apiapp import views
from django.conf.urls import url
from rest_framework import routers
from django.conf.urls import include

# 作者:上海悠悠,QQ交流群:750815713

router = routers.DefaultRouter()
router.register(r'cards', views.CardViewSet)

urlpatterns = [
    url(r'^api/v1/login/$', views.LoginViewSet.as_view()),
    url(r'^', include(router.urls)),
]

Test Interface

First obtain the login token, to copy out the token values: 1c0debb44fa0054d312616e7000ae78ce396df8e

{
    "code": 0,
    "msg": "login success!",
    "username": "test",
    "token": "1c0debb44fa0054d312616e7000ae78ce396df8e"
}

Adding to access bank card account interface, you need to bring token in the head, in the format

Authorization: Token 1c0debb44fa0054d312616e7000ae78ce396df8e

Bring token to request the time, you can normally add success

View database tables have data card new success

If the token error, or there will be no token 401 Unauthorized

Guess you like

Origin www.cnblogs.com/yoyoketang/p/11518524.html