【问题标题】:Django rest-framework Social Oauth2: How to set permission classes per view or methodDjango rest-framework Social Oauth2:如何为每个视图或方法设置权限类
【发布时间】:2019-11-25 18:47:28
【问题描述】:

我想使用Django rest-framework Social Oauth2为每个视图或方法设置权限。

我应该如何为每个视图或方法设置权限?

起初,我尝试在 settings.py 中设置“DEFAULT_AUTHENTICATION_CLASSES”。但是有些方法不需要认证,我想设置AllowAny。因此,我尝试将装饰器设置为该方法,但它不起作用。

settings.py

REST_FRAMEWORK = {   
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
}

views.py

@permission_classes([AllowAny, ])
@api_view(['POST'])
def someMethod(request):
    return foo

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    我自己解决了。在 settings.py 上注释掉 DEFAULT_AUTHENTICATION_CLASSES。并在views.py 上导入了这些Authentification 和authentication_classes。

    settings.py

    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            # 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
            # 'rest_framework_social_oauth2.authentication.SocialAuthentication',
        ),
    }
    

    views.py

    
    from rest_framework.decorators import authentication_classes
    from oauth2_provider.contrib.rest_framework import OAuth2Authentication
    from rest_framework_social_oauth2.authentication import SocialAuthentication
    
    class SampleViewSet(viewsets.ViewSet):
        authentication_classes = [OAuth2Authentication, SocialAuthentication]
    
        def someMethodNeedAuth:
             return foo
    
    
    @authentication_classes([AllowAny, ])
    @api_view(['POST'])
    def someMethodAllowAny(request):
        return bar
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-19
      • 2015-05-18
      • 2013-11-15
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2016-08-27
      相关资源
      最近更新 更多