403 response for POST/PUT/DELETE request in spring boot + spring security application

一个人想着一个人 提交于 2020-01-17 02:39:11

问题


I am using spring security in my spring boot rest app. Get requests are working fine but POST/PUT/DELETE request are giving "403 Forbidden". Below is my code snippet. UI is in 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;
    }

}

Browser response:


回答1:


Disable csrf in config

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


来源:https://stackoverflow.com/questions/53274610/403-response-for-post-put-delete-request-in-spring-boot-spring-security-applic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!