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

前端 未结 7 2046
忘了有多久
忘了有多久 2020-12-02 21:06

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

相关标签:
7条回答
  • 2020-12-02 21:07

    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;
        }
    
    0 讨论(0)
  • 2020-12-02 21:10

    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.

    0 讨论(0)
  • 2020-12-02 21:16

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

    Ex:

    this.http.put<class>(url, body, { withCredentials: true });
    
    0 讨论(0)
  • 2020-12-02 21:25

    On my team, the problem was that we were using an absolute path instead of a relative path.

    So do not use an absolute path like:

    this.http.post<any>("https://example.com/api/endpoint",data)
    

    Use

    this.http.post<any>("api/endpoint",data)
    

    Or use

    this.http.post<any>("//example.com/api/endpoint",data)
    

    This is because absolute paths are explicitly ignored by Angular code on HttpClientXsrfModule (see)

    0 讨论(0)
  • 2020-12-02 21:25
        request = request.clone({
            withCredentials: true
          });
    

    In InterceptService, this works with me

    0 讨论(0)
  • 2020-12-02 21:28

    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

    0 讨论(0)
提交回复
热议问题