【问题标题】:Can not create a post request include crsf in angularjs无法在angularjs中创建包含crsf的发布请求
【发布时间】:2018-01-10 15:36:12
【问题描述】:

我想将数据发布到 django 应用程序,我使用 angularjs http 发布。当我发布数据时,我得到一个 403 禁止。因此,我将我的 Angular 脚本更改为:

var app = angular.module('omCenterLoginApp',['ngCookies']);
 app.config(['$httpProvider', function ($httpProvider,$cookies) {
      $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
      $httpProvider.defaults.xsrfCookieName = 'csrftoken';
}])

app.controller('omCenterLoginContr',function($scope,$http){
    $scope.login = function(){
        var user = $scope.username;
        var password = $scope.password;
        $http({
            method: 'POST',
            url:'http://172.100.1.8:8080/api/test/',
            data:{user:password},
        }).then(function successCallback(response){
               console.log(response.data)
               },function errorCallback(response){
                console.log(response.data) 
            })
    }
});

我加了,

$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.xsrfCookieName = 'csrftoken';

但是,当我尝试发布它时,仍然得到响应 403 错误。 我检查了 post http 标头。里面没有 X-CSRFToken。

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:2
Content-Type:application/json;charset=UTF-8
Host:172.100.1.8:8080
Origin:http://172.100.1.8
Pragma:no-cache
Referer:http://172.100.1.8/login.html?
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

我的angularjs版本:1.5.8

但是当我尝试访问 url http://172.100.1.8:8080/api/test/,I 可以得到 回应。

http 请求是:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Cookie:sessionid=jbg90n8118w6qhcmbom8txctui2s59ca; csrftoken=tBsTGiBtcgMOw8MFslu6v3UJEdSXkmYF
Host:172.100.0.48:8080
Pragma:no-cache
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 

csrftoken 存在。

提前感谢您的帮助。

【问题讨论】:

  • 您能检查一下:cookie 是否存在?
  • 我遇到了完全相同的问题,cookie 确实存在但没有被发送。相同版本的 AngularJs 和一切。这里有任何可能的解决方案的更新吗?

标签: angularjs django http csrf


【解决方案1】:

这是通过单页应用程序使用 CSRF 的一种相当复杂的方式,除非您通过 Django 提供页面。 在使用单页应用程序访问 Django API 时,请尝试使用其他形式的身份验证,例如 Token Auth 或 JWT Auth。这可以通过出色的Django Rest Framework 轻松实现。即使您不喜欢使用它,您也可以简单地使用一些身份验证库,例如django-oauth。只是为了测试,但是您可以使用 csrf_exempt 装饰器来允许您的 Angular 应用程序在没有 csrf 令牌的情况下发送请求(尽管您正在打开代码上的漏洞)。使用某种身份验证始终是一个好习惯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2015-06-15
    • 2017-09-10
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多