【问题标题】:Angular 4 - setting withCredentials on every request - cors cookieAngular 4 - 在每个请求上设置 withCredentials - cors cookie
【发布时间】:2018-04-28 12:44:19
【问题描述】:

我的 Angular 客户端与后端分离,并且我在后端启用了 cors,一切正常,除了我的身份验证失败,因为 cookie 未添加到请求中。

在网上搜索后发现我应该在每个http请求上设置{withCredentials : true}。我设法在一个请求上做到了,它可以工作,但不是所有的请求。

我尝试使用 BrowserXhr How to send "Cookie" in request header for all the requests in Angular2?,但它不起作用,而且它也已被弃用 afaik。

我也尝试过 RequestOptions,但没有成功。

如何在每个 http 请求上设置 {withCredentials: true}

稍后编辑:

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

【问题讨论】:

  • 我添加了对 mea 有效的代码
  • 见我的example

标签: angular http cookies oauth-2.0 cross-domain


【解决方案1】:

您可以使用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 {}

Source and full explanation

【讨论】:

  • avoid link only answers。答案“仅仅是指向外部网站的链接”may be deleted
  • @Quentin 道歉,我用代码示例更新了我的答案。
  • 请注意,这只适用于使用@angular/common/http 的请求,而不是使用@angular/http。
  • 这似乎只适用于获取请求,关于 post 和 put 的任何建议?
  • @MGDavies HttpInterceptor 不仅限于GET 请求,还应该适用于POSTPUT
【解决方案2】:

另一种可能更简单的方法是创建自己的ApiService。它将使用注入的HttpClient。所有 XHR 请求都将直接使用 ApiService 而不是 HttpClient。

这是一个示例实现:

https://github.com/gothinkster/angular-realworld-example-app/blob/63f5cd879b5e1519abfb8307727c37ff7b890d92/src/app/core/services/api.service.ts

我修改的部分代码:

@Injectable()
export class ApiService {

  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
    withCredentials: true // to allow cookies to go from "https://localhost:4567" to "http://localhost:5678"
  };

  constructor(
    private http: HttpClient
  ) { }

  private formatErrors(error: any) {
    return throwError(error.error);
  }

  get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.api_url}${path}`, { params })
      .pipe(catchError(this.formatErrors));
  }

  put(path: string, body: Object = {}): Observable<any> {
    return this.http.put(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      this.httpOptions
    ).pipe(catchError(this.formatErrors));
  }

  post(path: string, body: Object = {}): Observable<any> {
    return this.http.post(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      this.httpOptions
    ).pipe(catchError(this.formatErrors));
  }

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 2015-08-10
    • 2019-05-07
    • 2016-07-21
    • 2012-04-26
    • 2019-12-04
    • 2014-11-09
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多