【问题标题】:Why I don't get authorization header?为什么我没有得到授权标头?
【发布时间】:2021-01-05 01:09:04
【问题描述】:

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

Axois 发送:

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

春天来了

 @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

【问题讨论】:

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


    【解决方案1】:

    我添加了 Bean:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-27
      • 2019-04-20
      • 1970-01-01
      • 2013-09-04
      • 2022-12-24
      • 2015-11-26
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多