|
| 1 | +package org.baeldung.spring; |
| 2 | + |
| 3 | +import org.baeldung.web.error.CustomAccessDeniedHandler; |
| 4 | +import org.springframework.beans.factory.annotation.Autowired; |
| 5 | +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; |
| 6 | +import org.springframework.context.annotation.Configuration; |
| 7 | +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; |
| 8 | +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; |
| 9 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 10 | +import org.springframework.security.config.annotation.web.builders.WebSecurity; |
| 11 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 12 | +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| 13 | + |
| 14 | +// @Configuration |
| 15 | +// @EnableAutoConfiguration |
| 16 | +// @EnableWebSecurity |
| 17 | +// @EnableGlobalMethodSecurity(prePostEnabled = true) |
| 18 | +public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter { |
| 19 | + |
| 20 | + @Autowired |
| 21 | + private CustomAccessDeniedHandler accessDeniedHandler; |
| 22 | + |
| 23 | + public SecurityWithCsrfConfig() { |
| 24 | + super(); |
| 25 | + } |
| 26 | + |
| 27 | + // java config |
| 28 | + |
| 29 | + @Override |
| 30 | + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { |
| 31 | + auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN"); |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public void configure(final WebSecurity web) throws Exception { |
| 36 | + web.ignoring().antMatchers("/resources/**"); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + protected void configure(final HttpSecurity http) throws Exception { |
| 41 | + // @formatter:off |
| 42 | + http |
| 43 | + .authorizeRequests() |
| 44 | + .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") |
| 45 | + .anyRequest().authenticated() |
| 46 | + .and() |
| 47 | + .httpBasic() |
| 48 | + .and() |
| 49 | + .exceptionHandling().accessDeniedHandler(accessDeniedHandler) |
| 50 | + ; |
| 51 | + // @formatter:on |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments