不要求对来自浏览器的GET请求进行身份验证

时间:2015-07-08 20:46:46

标签: django django-rest-framework

此问题与Do not require authentication for OPTIONS requests

密切相关

我的settings.py

REST_FRAMEWORK = {
    'UNICODE_JSON': True,
    'NON_FIELD_ERRORS_KEY': '__all__',
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'platformt_core.something.permissions.DjangoObjectPermissionsOrOptions',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'ALLOWED_VERSIONS': ['v1'],
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    'TEST_REQUEST_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    )
}

platformt_core /东西/ permissions.py

from rest_framework.permissions import DjangoObjectPermissions

OPTIONS_METHOD = 'OPTIONS'

class DjangoObjectPermissionsOrOptions(DjangoObjectPermissions):
    def has_permission(self, request, view):
        if request.method == OPTIONS_METHOD:
            return True
        else:
            return super(DjangoObjectPermissions, self).has_permission(request, view)

当我从浏览器执行此请求时:

GET /api/passenger/v1/order/ HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=3XytVl8Oh2PJxcSs1ufI9TIZMOTC5Pix

我期待在http://www.django-rest-framework.org/topics/documenting-your-api/

中描述的类似“自我描述API”的东西

但我得到了:

HTTP/1.0 401 UNAUTHORIZED
Date: Wed, 08 Jul 2015 20:45:23 GMT
Server: WSGIServer/0.1 Python/2.7.6
Content-Type: application/json;q=0.8; charset=utf-8
WWW-Authenticate: Token
Allow: POST, OPTIONS

{"detail":"Authentication credentials were not provided."}

有没有一种巧妙的方法来实现这一目标?我的意思是我希望有可浏览的API,但API请求仍然应该通过身份验证来保护。

1 个答案:

答案 0 :(得分:0)

你能不能使用?

'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticatedOrReadOnly',)

这将允许对未经身份验证的用户进行只读访问。