Angular 6 does not add X-XSRF-TOKEN header to http request

有些话、适合烂在心里 提交于 2019-12-17 18:18:54

问题


I've read the docs and all the related questions on SO, but still Angular's XSRF mechanism isn't working for me: in no way I can make a POST request with the X-XSRF-TOKEN header appended automatically.

I have an Angular 6 app with a login form.

It's part of a Symfony (PHP 7.1) website, and the Angular app page, when served from Symfony, sends the correct Cookie (XSRF-TOKEN):

My app.module.ts includes the right modules:

// other imports...
import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

// ...
@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    NgbModule.forRoot(),
    BrowserModule,
    // ...
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    }),
    // other imports
  ],
  providers: [],
  entryComponents: [WarningDialog],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Then, inside a Service's method, I'm making the following http request (this.http is an instance of HttpClient):

this.http
    .post<any>('api/login', {'_username': username, '_pass': password})
    .subscribe(/* handler here */);

The post request never sends the X-XSRF-TOKEN header. Why?


回答1:


The problem once again is Angular's poor documentation.

The fact is, Angular will add the X-XSRF-TOKEN header only if the XSRF-TOKEN cookie was generated server-side with the following options:

  • Path = /
  • httpOnly = false (this is very important, and fully undocumented)

Besides, the Angular app and the URL being called must reside on the same server.

Reference: this Angular Github issue




回答2:


Slightly off topic, but for others who come here, I resolved this issue in the back end by the following (for spring-boot)

     /**
     * CORS config - used by cors() in configure() DO NOT CHANGE the METDHO NAME
     * 
     * @return
     */
    @Bean()
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Lists.newArrayList("http://localhost:4200"));
        configuration.setAllowedMethods(Lists.newArrayList("GET", "POST", "OPTIONS"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Lists.newArrayList("x-xsrf-token", "XSRF-TOKEN"));
        configuration.setMaxAge(10l);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }



回答3:


Make sure, your server allows X-CSRF-Token headers on when browser requests OPTIONS method.

Example:

Access-Control-Allow-Headers: X-CSRF-Token, Content-Type

Reference: MDN Docs




回答4:


After struggling for countless hours, the solution that worked for us was changing the request (in Angular) from 'https://example.com' to '//example.com'.

None of the other solutions worked for us.




回答5:


You should put on the service on the frontend this { withCredentials: true }

Ex:

this.http.put<class>(url, body, { withCredentials: true });


来源:https://stackoverflow.com/questions/50510998/angular-6-does-not-add-x-xsrf-token-header-to-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!