我正在尝试获取对我的DRF API的访问权限,并且尝试对我的API进行身份验证,但是由于在收到禁止访问之前未收到403 HTTP错误(未设置CSRF cookie),因此无法发布用户名/密码(数据)。错误,然后我将视图更改为基于DRF类的视图,现在我陷入了该错误,无法将任何内容发布到我的API
请求(在Django项目之外)
payload = {'username': 'user', 'password': '****'}
r = requests.get('http://website/api/login/', data=payload)
网址
app_name = 'api'
urlpatterns = [
url(r'^login/$', views.login_to_api.as_view(), name = "login_to_api"),
观看次数
class CustomerListAPIView(generics.ListAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class CustomerRetrieveAPIView(generics.RetrieveAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class login_to_api(APIView):
def post(self, request):
if request.method == "POST":
(logic)
的HTML
<form id="login-form" method="post" action="{% url 'api:login_to_api' %}" >
{% csrf_token %}
<table class="table">
<tr>
<td><label >Username</label></td>
<td><input id="username" name="username" type="text" class="form-control"></td>
</tr>
<tr>
<td><label >Password</label></td>
<td><input id="password" name="password" type="password" class="form-control"></td>
</tr>
{%csrf_token%}
</table>
<input type="submit" value="Login" class="btn btn-primary pull-right" />
设定
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
#'rest_framework.authentication.SessionAuthentication',
)#,'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', )
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
任何帮助将不胜感激
我修复它的方法是从设置中删除is_authenticated
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
然后在permission_classes = (IsAuthenticated,)
除了登录视图之外的每个基于分类的视图中放置的视图中,这样我就可以将凭据发布到该视图中进行登录,并在我的请求逻辑中创建一个会话,然后转到登录视图,然后再请求其他任何视图需要的意见
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句