Angular 6 Http Interceptors, request headers not modified

后端 未结 1 409
Happy的楠姐
Happy的楠姐 2021-01-28 08:19

I created an interceptor to add an authorization header to each request sent by the client, here is the code :

import { HttpInterceptor, HttpRequest, HttpHandler         


        
1条回答
  •  无人共我
    2021-01-28 08:44

    Your problem resides into backend services. For security reasons by default only some headers are accepted, the others are ignored.

    To fix your problem you need to setup custom accepted headers. Authorization header, even if is like a standard for JWT, is considered a custom header.

    I can give you an example of my Spring Security configuration:

    @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("DELETE");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    

    Note the line

    config.addAllowedHeader("*");
    

    That means that my REST services accept all possible headers sent by the client. Obviously it's not a good configuration, you should limit allowed headers and other things to match your needs, as restricted as is possible.

    Obviously if you don't use Spring Security you need to find the way to do the same thing with yout language/framework.

    This is my SecurityConfig.java It's a bit different from yours. Try this and let me know

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private JwtAuthenticationEntryPoint unauthorizedHandler;
    
        @Autowired
        private JwtTokenUtil jwtTokenUtil;
    
        @Autowired
        private WLUserDetailsService userDetailsService;
    
        @Value("${jwt.header}")
        private String tokenHeader;
    
        @Value("${jwt.route.authentication.path}")
        private String authenticationPath;
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                    .passwordEncoder(passwordEncoderBean());
        }
    
        @Bean
        public PasswordEncoder passwordEncoderBean() {
            return new BCryptPasswordEncoder();
        }
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
                    // we don't need CSRF because our token is invulnerable
                    .csrf().disable()
    
                    // TODO adjust CORS management
                    .cors().and()
    
                    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
    
                    // don't create session
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
    
                    .authorizeRequests()
    
                    .antMatchers("/auth/**").permitAll()
                    .anyRequest().authenticated();
    
            // Custom JWT based security filter
            JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
            httpSecurity
                    .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    
    //        // disable page caching
    //        httpSecurity
    //                .headers()
    //                .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
    //                .cacheControl();
        }
    
        @Override
        public void configure(WebSecurity web) {
            // AuthenticationTokenFilter will ignore the below paths
            web
                    .ignoring()
                    .antMatchers(
                            HttpMethod.POST,
                            authenticationPath
                    )
    
                    // allow anonymous resource requests
                    .and()
                    .ignoring()
                    .antMatchers(
                            HttpMethod.GET,
                            "/",
                            "/*.html",
                            "/favicon.ico",
                            "/**/*.html",
                            "/**/*.css",
                            "/**/*.js"
                    );
        }
    
    
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("*");
    //        config.addExposedHeader("Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
    //                "Content-Type, Access-Control-Request-Method, Custom-Filter-Header");
            config.addAllowedHeader("*");
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("DELETE");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    
    }
    

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