Django Angular 403 Django不接受CSRF-cookie:“CSRF令牌丢失或不正确。”

时间:2018-05-26 18:54:13

标签: django angular cookies django-rest-framework csrf

我正在尝试使用Angular6和Django创建SPA。我有一个问题,Django不接受我发送请求的csrftoken cookie。 我的settings.py中有CSRF_USE_SESSIONS = False

当获取请求设置cookie时,这是来自浏览器控制台的图片: Successful get with set cookie.

以下是使用相同Cookie的后请求:Postcookie

cookie在请求之间没有变化,因为如果我之后再做另一个get-request,我会得到相同的cookie集。

以下是如何以角度设置Cookie策略:

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 { }

我的Django视图代码:

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)

编辑:

我还尝试从cookie中提取令牌值,并将其作为'csrfmiddlewaretoken'与其余的帖子数据一起发布。

1 个答案:

答案 0 :(得分:0)

最后得到了@jason。

我使用的是XSRFStrategy的弃用版本。工作代码现在在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 { }

HttpXSRFInterceptor.ts看起来像这样:

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);
    }
}

为简洁起见,成功的请求和响应如下所示: enter image description here