Angular 4 - 在每个请求中设置withCredentials - cors cookie [英] Angular 4 - setting withCredentials on every request - cors cookie
问题描述
我的角度客户端与后端分离,我在后端启用了cors,一切正常,但我的身份验证失败,因为cookie未添加到请求中。
My angular client is separated from the backend and I have enabled cors on the backend, everything works fine except the fact that my authentication fails because the cookie is not added to requests.
在线搜索后,我发现我应该在每个http请求中设置 {withCredentials:true}
。我设法在一个请求上执行它并且它可以工作,但不是在所有请求上。
After searching online I found that I should set {withCredentials : true}
on every http request. I managed to do it on a single request and it works, but not on all the requests.
我尝试使用BrowserXhr 如何发送Cookie在Angular2中的所有请求的请求标头中?但是它不起作用并且它也被弃用了。
I tried using BrowserXhr How to send "Cookie" in request header for all the requests in Angular2? but it doesn't work and it's also deprecated afaik.
我也尝试了RequestOptions但它没有用。
I also tried RequestOptions but it didn't work.
如何在每个http请求中设置{withCredentials:true}?
What can I do to set {withCredentials: true} on every http request?
稍后编辑:
@Injectable()
export class ConfigInterceptor implements HttpInterceptor {
constructor(private csrfService: CSRFService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.csrfService.getCSRF() as string;
const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
return next.handle(credentialsReq);
}
}
推荐答案
你可以使用 HttpInterceptor
。
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
接下来你必须提供它:
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor ,
multi: true
}
]
})
export class AppModule {}
这篇关于Angular 4 - 在每个请求中设置withCredentials - cors cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!