为什么我没有获得授权标头?

时间:2020-09-18 05:38:22

标签: java spring-boot spring-security axios jwt

我使用Spring框架。如果我使用邮递员发送请求,则会获得授权标头,但是如果使用Axois,则不会获得授权标头。有什么问题吗?

Axois发送:

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

Cors春季

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

Spring安全配置:

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

在此处获取标题:

 @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 个答案:

答案 0 :(得分:0)

我添加了Bean:

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

}

相关问题