Newer
Older
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Value("${cors.allowed.origin}")
private String corsAllowedOrigin;
// CORS are necessary only for development (API access from npm server)
if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
}
/**
* The authentication is ignored for these endpoints. The "/ws" endpoints
* (web service API for programmatic access) are protected by the custom
* WebServiceAuthorizationFilter that checks BasicAuth for GMS clients.
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/ws/**", "/error");
}
/**
* Checks the BasicAuth for GMS clients.
*/
@Bean
public FilterRegistrationBean webServiceAuthorizationFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebServiceAuthorizationFilter());
bean.addUrlPatterns("/ws/*");
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
/**
* CORS are necessary only for development (API access from npm server).
*/
@Bean
@Profile("dev")
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.DELETE);
config.setAllowedOrigins(Arrays.asList(corsAllowedOrigin));
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}