I'm trying to create an SPA using Angular6 combined with Django. I'm having a problem with Django not accepting the csrftoken cookie I'm sending with my requests. CSRF_USE_SESSIONS = False
in my settings.py
Here's a picture from the browser console when the cookie gets set by a get-request:
And here is the post-request using that same cookie:
The cookie isn't changing between request, because if I do another get-request after that I get the same cookie-set.
Here's how the cookie strategy is set up in angular:
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http'
import ....
@NgModule({
declarations: [
AppComponent,
RegisterComponent,
LoginComponent,
AlertComponent,
ProfileComponent,
RegisterinvoiceComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
HttpModule
],
providers: [
{
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
And my Django view-code:
class InvoiceViewSet(viewsets.ModelViewSet):
queryset=Invoices.objects.all()
serializer_class=InvoiceSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
@method_decorator(ensure_csrf_cookie)
def create(self, request):
serializer=InvoiceSerializer(data=request.data)
if serializer.is_valid():
user=request.user
...
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Invoice could not be created with received data',
}, status=status.HTTP_400_BAD_REQUEST)
Ëdit:
I have also tried extracting the token value from the cookie and posting that as 'csrfmiddlewaretoken' with the rest of the post data.
Finally got it thanks to @jason.
I was using a deprecated version of the XSRFStrategy. Working code now looks like this in Angular:
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS, HttpClientXsrfModule, HttpXsrfTokenExtractor } from '@angular/common/http';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http'
import { AppComponent } from './app.component';
import ...
import { HttpXSRFInterceptor } from './_providers';
@NgModule({
declarations: [
AppComponent,
RegisterComponent,
LoginComponent,
AlertComponent,
ProfileComponent,
RegisterinvoiceComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
HttpModule,
HttpClientXsrfModule.withOptions({
cookieName: 'csrftoken',
headerName: 'X-CSRFToken'
})
],
providers: [
{
provide: HTTP_INTERCEPTORS, useClass: HttpXSRFInterceptor, multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
With the HttpXSRFInterceptor.ts looking like this:
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClientXsrfModule, HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'
import { Observable } from 'rxjs';
@Injectable()
export class HttpXSRFInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-CSRFToken';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)){
req=req.clone({ headers: req.headers.set(headerName, token)})
}
return next.handle(req);
}
}
For brevity a successful request and response looks like this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.