[英]Django Angular 403 Django not accepting CSRF-cookie: “CSRF token missing or incorrect.”
I'm trying to create an SPA using Angular6 combined with Django. 我正在尝试使用Angular6与Django结合创建SPA。 I'm having a problem with Django not accepting the csrftoken cookie I'm sending with my requests.
Django无法接受我随请求发送的csrftoken cookie时出现问题。
CSRF_USE_SESSIONS = False
in my settings.py CSRF_USE_SESSIONS = False
我的settings.py中CSRF_USE_SESSIONS = False
Here's a picture from the browser console when the cookie gets set by a get-request: 这是当浏览器通过get-request设置cookie时的图片:
And here is the post-request using that same cookie: 这是使用相同cookie的后期请求:
The cookie isn't changing between request, because if I do another get-request after that I get the same cookie-set. Cookie在请求之间没有变化,因为如果在此之后执行另一个get-request,我将获得相同的cookie集。
Here's how the cookie strategy is set up in angular: 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 { }
And my Django view-code: 还有我的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)
Ëdit: 编辑:
I have also tried extracting the token value from the cookie and posting that as 'csrfmiddlewaretoken' with the rest of the post data. 我还尝试从cookie中提取令牌值,并将其作为“ csrfmiddlewaretoken”与其余的发布数据一起发布。
Finally got it thanks to @jason. 最后感谢@jason。
I was using a deprecated version of the XSRFStrategy. 我使用的XSRFStrategy版本已弃用。 Working code now looks like this in Angular:
现在,工作代码在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: 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);
}
}
For brevity a successful request and response looks like this: 为简便起见,成功的请求和响应如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.