// .cors() uses by default uses a Bean by the name of corsConfigurationSource
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
//get origin from application properties
List<String> allowOrigins = Arrays.asList(origin);
configuration.setAllowedOrigins(allowOrigins);
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
//in case authentication is enabled this flag MUST be set, otherwise CORS requests will fail
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
private CookieCsrfTokenRepository csrfTokenRepository() {
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
repository.setSecure(false);
return repository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//hasAuthority(‘ROLE_ADMIN') is similar to hasRole(‘ADMIN')
//because the ‘ROLE_‘ prefix gets added automatically.
//hasRole(myString) ads "ROLE_" to string and checks that way.
//for instance if in database we have "ROLE_ADMIN" and we provide hasRole("ADMIN") it will work.
// .cors() uses by default uses a Bean by the name of corsConfigurationSource
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.cors().configurationSource(corsConfigurationSource())
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.authorizeRequests()
.antMatchers("/api/utility/**").permitAll()
.antMatchers("/api/security/auth/**").permitAll()
.antMatchers("/api/security/getCsrfToken").permitAll()
.antMatchers("/api/security/user/getUser").authenticated()
.antMatchers("/api/security/user/changePassword").authenticated();
// .anyRequest().authenticated(); http.headers().xssProtection() .and().contentSecurityPolicy("default-src 'self'; style-src 'self' 'unsafe-inline'; form-action 'self';"); }