Django Rest Framework。使用JSONWebTokenAuthentication的自定义权限

时间:2017-06-02 22:34:33

标签: django django-rest-framework

我需要为我的一个端点编写自定义权限(源自#include <stdio.h> #include <stdlib.h> #include <elf.h> #include <string.h> void print_item(FILE* fd, Elf64_Ehdr eh, Elf64_Shdr sh_table[]) { int i; char* sh_str; char* buff; buff = malloc(sh_table[eh.e_shstrndx].sh_size); if(buff != NULL) { fseek(fd, sh_table[eh.e_shstrndx].sh_offset, SEEK_SET); fread(buff, 1, sh_table[eh.e_shstrndx].sh_size, fd); } sh_str = buff; for(i=0; i<eh.e_shnum; i++) { if(!strcmp(".mydata", (sh_str + sh_table[i].sh_name))) { printf("Found section\t\".mydata\"\n"); printf("at offset\t0x%08x\n", (unsigned int)sh_table[i].sh_offset); printf("of size\t\t0x%08x\n", (unsigned int)sh_table[i].sh_size); break; } } /*Code to print or store string data*/ if (i < eh.e_shnum) { char *mydata = malloc(sh_table[i].sh_size); fseek(fd, sh_table[i].sh_offset, SEEK_SET); fread(mydata, 1, sh_table[i].sh_size, fd); puts(mydata); } else { // .mydata section not found } } int main() { FILE* fp = NULL; //Pointer used to access current file char* program_name; Elf64_Ehdr elf_header; //Elf header Elf64_Shdr* sh_table; //Elf symbol table program_name = "/home/Testing/TEST"; fp = fopen(program_name, "r"); fseek(fp, 0, SEEK_SET); fread(&elf_header, 1, sizeof(Elf64_Ehdr), fp); sh_table = malloc(elf_header.e_shentsize*elf_header.e_shnum); fseek(fp, elf_header.e_shoff, SEEK_SET); fread(sh_table, 1, elf_header.e_shentsize*elf_header.e_shnum, fp); print_item(fp, elf_header, sh_table); return 0; } ),其中:

如果方法为BasePermission,则对所有人开放(例如,返回true)。 但是,如果方法是POSTPUT,则应使用GET对其进行身份验证,以确定是清除还是拒绝请求。

通常,我知道如何将其添加到我的JSONWebTokenAuthentication

APIView

但是,如果我的自定义权限类中的authentication_classes = ([JSONWebTokenAuthentication])方法为JSONWebTokenAuthenticationHTTP,我如何检查用户是否已使用PUT进行了身份验证?某处有GET吗?

1 个答案:

答案 0 :(得分:1)

您需要为视图撰写自定义权限,

<强> permissions.py

class CustomPermission(BasePermission):

    def has_permission(self, request, view):
        if (request.method =='POST' or (request.user and request.user.is_authenticated())):
            return True
        return False

然后,您需要添加到settings.py,

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', ),
         }

然后将权限添加到视图的permission_classes中,

from .permissions import CustomPermission

class YourView(APIView):
    permission_classes = (CustomPermission, )