简体   繁体   English

向 django rest api 添加权限

[英]Adding permissions to a django rest api

I am working on a django rest api and i want to add permission to it.我正在研究 django rest api,我想为其添加权限。 I decided to go with IsAuthenticatedOrReadOnly to allow none authenticated people to read only and allow authenticated people to add data我决定 go 与 IsAuthenticatedOrReadOnly 允许没有经过身份验证的人只读并允许经过身份验证的人添加数据

setting.py:设置.py:

REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': [

        'rest_framework.permissions.IsAuthenticated',
    ]}

views.py:视图.py:

@api_view(['GET','POST'])

@permission_classes([IsAuthenticatedOrReadOnly])

def list_drinks(request, format=none):
  
   if request.method ==  'GET':

        drinks = Drink.objects.all()

        serializer = DrinkSerializer(drinks, many=True)

        return Response(serializer.data)

    if request.method == 'POST':

        serializer = DrinkSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

when i try to access the api without authentification, i can only read but when i try to do a modification while adding a username and a password, i get the message "detail": "You do not have permission to perform this action."当我尝试在没有身份验证的情况下访问 api 时,我只能阅读,但是当我尝试在添加用户名和密码时进行修改时,我收到消息“详细信息”:“您无权执行此操作。” even though i am authenticated as admin (a superuser)即使我被认证为管理员(超级用户)

what's the problem?有什么问题?

Make sure you have the necessary authentication classes in your REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] settings.确保您的REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]设置中有必要的身份验证类。

For basic authentication add "rest_framework.authentication.BasicAuthentication" to the list.对于基本身份验证,将"rest_framework.authentication.BasicAuthentication"添加到列表中。

If you are using the browsable API you need to add session authentication "rest_framework.authentication.SessionAuthentication"如果您使用的是可浏览的 API,您需要添加 session 身份验证"rest_framework.authentication.SessionAuthentication"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM