Skip to content

Instantly share code, notes, and snippets.

@novoj
Created February 27, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save novoj/f3e8a7a47e262ba79776089aeb98092c to your computer and use it in GitHub Desktop.
Save novoj/f3e8a7a47e262ba79776089aeb98092c to your computer and use it in GitHub Desktop.
Spring Security Java Configuration
@Configuration
@EnableWebMvcSecurity
@ComponentScan(basePackageClasses = UserRepositoryUserDetailsService.class)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Autowired
private PermissionEvaluator permissionEvaluator;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler handler =
new DefaultMethodSecurityExpressionHandler();
handler.setPermissionEvaluator(permissionEvaluator);
return handler;
}
}
@Order(1)
@Configuration
static class H2WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers()
.cacheControl()
.contentTypeOptions()
.httpStrictTransportSecurity()
.and()
.requestMatchers()
.antMatchers("/h2/**")
.and()
.formLogin()
.loginPage("/login")
.and()
.authorizeRequests()
.anyRequest().hasRole("ADMIN");
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**","/signup").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment