【问题标题】:Spring Security still returns HTTP 403 when HTTP request is created from remote host当从远程主机创建 HTTP 请求时,Spring Security 仍然返回 HTTP 403
【发布时间】:2021-04-23 14:18:31
【问题描述】:

情况

这是我的 Spring 安全配置,当我从 localhost 创建请求并且应用程序也在 localhost 运行时,它可以工作。

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    
    http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/client/**")
        .hasRole(HttpClientType.CLIENT.name())
        .antMatchers("/**")
        .hasRole(HttpClientType.USER.name())
        .anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(restAuthenticationEntryPoint)
        .accessDeniedHandler(restAuthorizationEntryPoint)
        .and()
        .addFilterBefore(jwtTokenFilter, BasicAuthenticationFilter.class)
        .csrf().disable().cors().disable();

  }

问题

当我将应用程序部署到生产服务器并从远程主机创建请求时,每次收到HTTP 403

附注我以为问题出在CORSCSRF 但即使我禁用它也不起作用。

【问题讨论】:

  • 尝试从 Postman 或 cUrl 发出请求。如果是 CORS,则 Postman 请求应该成功。
  • 我正在使用 Postman,Authentication 成功。
  • 那么我很确定这是 CORS 问题。使用.cors().disable() 时,Spring Security 非常不直观。 cors().disable() 根本不会禁用 cors 安全过滤器,而只会应用默认的 cors 配置
  • 我认为 CORS 不会返回 403。尝试删除 .antMatchers("/**").hasRole(...) 并更改为 .anyRequest().hasRole(...) 而不是 .anyRequest().authenticated()
  • 您使用的是嵌入式 servlet 容器吗?还是部署在 Tomcat 等外部 Web 容器上?

标签: java spring-boot spring-security authorization


【解决方案1】:

cors().disable() 根本不会禁用 cors 安全过滤器,而只会应用默认的 cors 配置。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    ...
    .cors().configurationSource(corsConfigurationSource())
    ...
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(List.of(CorsConfiguration.ALL)); 
    configuration.setAllowedMethods(List.of(CorsConfiguration.ALL));
    configuration.setAllowedHeaders(List.of(CorsConfiguration.ALL));
    configuration.setAllowCredentials(true);
  
   // ideally CorsConfiguration.ALL should not be used in production

    configuration.addExposedHeader(HttpHeaders.AUTHORIZATION); // The headers you expose in response

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();       
    source.registerCorsConfiguration("/**", configuration);

    return source;
}

【讨论】:

  • 不,没有帮助。
【解决方案2】:

你是否在课堂上使用@EnableWebSecurity 来启用mvc 安全设置?使用 .sessionRegistry(sessionRegistry()) 进行测试

@Bean
public SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 2018-12-13
    • 2011-08-19
    • 2017-11-17
    • 2020-07-09
    • 2022-07-07
    • 1970-01-01
    • 2022-01-16
    • 2019-02-08
    相关资源
    最近更新 更多