7π
Canβt you make a call like this:
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
The data
can be whatever you wish to pass and then just append &{{csrf_token}}
to that.
In your resource params:{}
, try adding csrfmiddlewaretoken:{{csrf_token}}
inside the params
Edit:
You can pass data to the request body as
item.$update({csrfmiddlewaretoken:{{csrf_token}}})
and to headers as
var csrf = '{{ csrf_token }}';
update:{method:'POST', headers: {'X-CSRFToken' : csrf }}
It is an undocumented issue
40π
I know this is more than 1 year old, but if someone stumbles upon the same issue, angular JS already has a CSRF cookie fetching mechanism (versions of AngularJS starting at 1.1.5), and you just have to tell angular what is the name of the cookie that django uses, and also the HTTP header that it should use to communicate with the server.
Use module configuration for that:
var app = angular.module('yourApp');
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
Now every request will have the correct django CSRF token. In my opinion this is much more correct than manually placing the token on every request, because it uses built-in systems from both frameworks (django and angularJS).
- [Django]-Django Projects as Desktop applications : how to?
- [Django]-How to remove models from django?
- [Django]-Annotate with latest related object in Django
1π
In recent angularjs version giving solution is not working . So i tried the following
-
First add django tag {% csrf_token %} in the markup.
-
Add a $http inspector in your app config file
angular.module('myApp').config(function ( $httpProvider) {
$httpProvider.interceptors.push('myHttpRequestInterceptor');
});
- Then define that myHttpRequestInterceptor
angular.module("myApp").factory('myHttpRequestInterceptor', function ( ) {
return {
config.headers = {
'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() }
}
return config;
}};
});
itβll add the X-CSRFToken in all angular request
And lastly you need to add the Django middleware β django.middleware.csrf.CsrfViewMiddleware'β
Itβll solve the CSRF issue
- [Django]-Can a dictionary be passed to django models on create?
- [Django]-Use django: from "python manage.py shell" to python script
- [Django]-Django: How can I call a view function from template?
0π
var app = angular.module('angularFoo', ....
app.config(["$httpProvider", function(provider) {
provider.defaults.headers.common['X-CSRFToken'] = '<<csrftoken value from template or cookie>>';
}])
- [Django]-Raise a validation error in a model's save method in Django
- [Django]-Django-object-permissions Vs django-guardian Vs django-authority
- [Django]-Django REST Framework: Setting up prefetching for nested serializers
0π
I use this:
In Django view:
@csrf_protect
def index(request):
#Set cstf-token cookie for rendered template
return render_to_response('index.html', RequestContext(request))
In App.js:
(function(A) {
"use strict";
A.module('DesktopApplication', 'ngCookies' ]).config(function($interpolateProvider, $resourceProvider) {
//I use {$ and $} as Angular directives
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
//Without this Django not processed urls without trailing slash
$resourceProvider.defaults.stripTrailingSlashes = false;
}).run(function($http, $cookies) {
//Set csrf-kookie for every request
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
});
}(this.angular));
For sending correct request you must convert object to param-form:
$http.post('/items/add/', $.param({name: 'Foo'}));//Here $ is jQuery
- [Django]-Using django signals in channels consumer classes
- [Django]-Get type of Django form widget from within template
- [Django]-How to use permission_required decorators on django class-based views
0π
I have checked in Angular 15 and Django 4.0 now can fetch csrf-token. Here is solution (is working):
- In services file add function
authorizeUser(username: string, password: string, csrfmiddlewaretoken: string): Observable<any>{
const url = 'http://localhost:8000/admin/login/?next=/admin/'
const encodedBody = new URLSearchParams();
encodedBody.set('username', username);
encodedBody.set('password', password);
encodedBody.set('csrfmiddlewaretoken', csrfmiddlewaretoken)
return this.http.post(url, encodedBody);
}
- Add component AdminComponent
export class AdminComponent implements OnInit, HttpInterceptor {
xsrf: string = <string>this.cookieExtractor.getToken()
form: FormGroup = new FormGroup({
username: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
}
);
submitted = false
- Add in previous component this important function
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': this.xsrf }),
withCredentials: true
});
return next.handle(request);
}
So the main problem which I have faced with writing application on both frontend and backend service that content-type must be application/x-www-form-urlencoded
and not application/json
(you can check via Postman sending request in Django-admin area). Hope that this solution will help you!
- [Django]-How do I check for last loop iteration in Django template?
- [Django]-Django unique_together not preventing duplicates
- [Django]-Return the current user with Django Rest Framework