2

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: Successful get with set cookie.

And here is the post-request using that same cookie: Postcookie

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.

Community
  • 1
  • 1
Marcus Grass
  • 1,043
  • 2
  • 17
  • 38
  • I have no idea how to use Angular, but when using standard AJAX request the data sent should be named `csrfmiddlewaretoken`. – politinsa May 26 '18 at 21:09
  • yeah when Djangos {% csrf_token %} it produces a hidden input element with the name 'csrfmiddlewaretoken' but when using cookie authentication the cookie token name is 'csrftoken', based on [these docs](https://docs.djangoproject.com/en/2.0/ref/csrf/) – Marcus Grass May 26 '18 at 21:16
  • did you see this https://stackoverflow.com/questions/46040922/angular4-httpclient-csrf-does-not-send-x-xsrf-token – Jason May 27 '18 at 16:01
  • @Jason Thank's a lot for that, the solution didn't work immediately, but it must be a header problem, I don't understand what else it might be! – Marcus Grass May 27 '18 at 18:58

1 Answers1

0

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: enter image description here

Marcus Grass
  • 1,043
  • 2
  • 17
  • 38