我正在尝试使用Angular6和Django创建SPA。我有一个问题,Django不接受我发送请求的csrftoken cookie。
我的settings.py中有CSRF_USE_SESSIONS = False
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'与其余的帖子数据一起发布。
答案 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);
}
}