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