Configuring CORS in Spring Security

Asked

Viewed 3,371 times

1

I need to configure Spring Security to accept requests from external applications. I do not know how to do, I have a project in Spring Boot and Spring Security where only accept request from the same origin. Must accept AJAX request using angular.

Codes:

Spring Security:

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImp userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TokenAuthenticationService getTokenAuthenticationService() {
        return new TokenAuthenticationService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/","/index.html","/recuperarSenha","/admin/**", "/app/**","/favicon.ico","/install/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().cacheControl();

        http.cors().disable() // disable csrf for our requests.
        .authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers(HttpMethod.GET,"/conectado").permitAll()
        .antMatchers(HttpMethod.POST,"/login").permitAll()
        .antMatchers(HttpMethod.GET,"/install/admin").permitAll()
        .antMatchers(HttpMethod.POST,"/login/recuperarSenha").permitAll()
        .antMatchers(HttpMethod.POST,"/api/**").permitAll()
        .anyRequest().authenticated()
        .and()
        // We filter the api/login requests
        .addFilterBefore(new JWTLoginFilter("/login", authenticationManager(), getTokenAuthenticationService()), UsernamePasswordAuthenticationFilter.class)
        // And filter other requests to check the presence of JWT in header
        .addFilterBefore(new JWTAuthenticationFilter(getTokenAuthenticationService()), UsernamePasswordAuthenticationFilter.class);

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());

    }

}

And Angular-js:

$scope.logar = function(login){

            $http.post("http://192.168.0.13:8088/onblox/login",login)
            .success(function(response){
                $scope.response1 = response;
            })
            .error(function(error){
            });

            }
  • Tried to use the annotation @CrossOrigin(origins = "ip") in your Rest Controller?

  • tried "@Crossorigin(Origins = "http://192.168.0.9:8085", maxAge = 3600) @Requestmapping(value="/login") public class Logincontroller extends Controllerimpl<Login, Long>{ more yet ta giving me error : No content to map due to end-of-input

  • 1

    Help yourself: https://github.com/gleydson/SystemEPCTG-RestServer/blob/master/src/main/java/br/org/estacaoluz/epctg/util/CorsFilterUtil.java In this project I am using Springboot on the back and angular4 on the front, with token authentication jwt and to configure Cors just add this class.

1 answer

2


Try:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
        //... seu codigo
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
   }
}

Another detail in your code is an excerpt:

http.cors().disable() // disable csrf for our requests.

Would not be:

http.csrf().disable()

?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.