【问题标题】:403 response for POST/PUT/DELETE request in spring boot + spring security applicationSpring Boot + Spring Security 应用程序中 POST/PUT/DELETE 请求的 403 响应
【发布时间】:2019-04-15 21:48:39
【问题描述】:

我在我的 Spring Boot Rest 应用程序中使用 Spring Security。获取请求工作正常,但 POST/PUT/DELETE 请求给出“403 Forbidden”。下面是我的代码sn-p。 UI 在 Angular 6 中

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CustomAuthorizationFilter customAuthorizationFilter = new CustomAuthorizationFilter(authenticationManager());
        customAuthorizationFilter.setUserService(userService);
        http.cors().and().authorizeRequests().anyRequest().authenticated().and().addFilter(customAuthorizationFilter);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security",
                "/swagger-ui.html", "/webjars/**");
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must
        // not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

浏览器响应:

【问题讨论】:

  • 403响应与CORS配置无关

标签: spring spring-mvc spring-boot spring-security


【解决方案1】:

在配置中禁用 csrf

http.csrf().disable().cors().and().....

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2021-02-26
    • 1970-01-01
    • 2019-10-17
    • 2019-12-26
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多