0
votes

I use the Spring framework. If I send a request using postman, I get the authorization header, but if I use Axois I don't get it. What is the problem?

Axois send:

axios({
  method: 'get',
  url: 'http://localhost:8081/api/posts',
  headers: { 'Authorization': 'Bearer_' + localStorage.getItem("username")} // Cookies.get('Token')
})

Cors in spring

 @Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedHeaders("*")
            .exposedHeaders("Authorization", "authorization")
            .allowedOrigins("*")
            .allowedMethods("*")
            .allowCredentials(false).maxAge(3600);;
}

Spring security config:

  @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(LOGIN_ENDPOINT, REGISTRATION_ENDPOINT).permitAll()
            .antMatchers(ADMIN_ENDPOINT).hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider));
}

Get the headers here:

 @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) req;
    Map<String, List<String>> headersMap = Collections.list(httpRequest.getHeaderNames())
            .stream()
            .collect(Collectors.toMap(
                    Function.identity(),
                    h -> Collections.list(httpRequest.getHeaders(h))
            ));

Postman request

Headers with postman

Headers with Axios

1

1 Answers

0
votes

I added Bean:

    @Bean                                           
    CorsConfigurationSource corsConfigurationSource() {
       final UrlBasedCorsConfigurationSource source = new 
       UrlBasedCorsConfigurationSource();
       CorsConfiguration config = new CorsConfiguration();
       config.addAllowedMethod("*");
       source.registerCorsConfiguration("/**", config.applyPermitDefaultValues());
       return source;
    }