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.