实际上,我们的后端使用请求标头中的Cookie对请求进行身份验证.我知道如果我设置标题"Cookie",它将拒绝.那么,有没有办法将Cookie发送到后端?
Thi*_*ier 67
我想有一个阶段,你要求服务器验证你.在此之后(如果验证成功),服务器将在响应中返回cookie.浏览器将存储此cookie并为每次调用再次发送它.
也就是说,在跨域请求(CORS)的情况下,您需要将withCredentialsXHR设置true为使浏览器在您的请求中添加cookie.
要使用Angular2启用此功能,我们需要按BrowserXhr如下所述扩展类:
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.withCredentials = true;
return <any>(xhr);
}
}
Run Code Online (Sandbox Code Playgroud)
并BrowserXhr使用扩展覆盖提供者:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅此问题:
编辑(跟随凶手的评论)
从RC2,您可以withCredentials直接在请求配置中使用该属性,如下所述:
this.http.get('http://...', { withCredentials: true })
Run Code Online (Sandbox Code Playgroud)
编辑(在[maxou]评论之后)
请记住在每个请求中包含withCredentials:true .
Jav*_*Net 17
在Angular5中你可以写一个Http拦截器:
auth.interceptor.ts
import { Observable } from 'rxjs/Observable';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
Run Code Online (Sandbox Code Playgroud)
并添加到app.module的providers数组中
app.module.ts
import { AuthInterceptor } from './services/auth.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,HttpClientModule,FormsModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45487 次 |
| 最近记录: |