|
| 1 | +package org.baeldung.security; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Autowired; |
| 4 | +import org.springframework.context.annotation.Bean; |
| 5 | +import org.springframework.context.annotation.Configuration; |
| 6 | +import org.springframework.security.access.AccessDecisionManager; |
| 7 | +import org.springframework.security.access.AccessDecisionVoter; |
| 8 | +import org.springframework.security.access.vote.AuthenticatedVoter; |
| 9 | +import org.springframework.security.access.vote.RoleVoter; |
| 10 | +import org.springframework.security.access.vote.UnanimousBased; |
| 11 | +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; |
| 12 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 13 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 14 | +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| 15 | +import org.springframework.security.web.access.expression.WebExpressionVoter; |
| 16 | +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; |
| 17 | + |
| 18 | +import java.util.Arrays; |
| 19 | +import java.util.List; |
| 20 | + |
| 21 | +@Configuration |
| 22 | +@EnableWebSecurity |
| 23 | +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { |
| 24 | + @Autowired |
| 25 | + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { |
| 26 | + // @formatter: off |
| 27 | + auth.inMemoryAuthentication() |
| 28 | + .withUser("user").password("pass").roles("USER") |
| 29 | + .and() |
| 30 | + .withUser("admin").password("pass").roles("ADMIN"); |
| 31 | + // @formatter: on |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + protected void configure(HttpSecurity http) throws Exception { |
| 36 | + // @formatter: off |
| 37 | + http |
| 38 | + // needed so our login could work |
| 39 | + .csrf() |
| 40 | + .disable() |
| 41 | + .authorizeRequests() |
| 42 | + .anyRequest() |
| 43 | + .authenticated() |
| 44 | + .accessDecisionManager(accessDecisionManager()) |
| 45 | + .antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER") |
| 46 | + .and() |
| 47 | + .formLogin() |
| 48 | + .permitAll() |
| 49 | + .and() |
| 50 | + .logout() |
| 51 | + .permitAll() |
| 52 | + .deleteCookies("JSESSIONID") |
| 53 | + .logoutSuccessUrl("/login"); |
| 54 | + // @formatter: on |
| 55 | + } |
| 56 | + |
| 57 | + @Bean |
| 58 | + public AccessDecisionManager accessDecisionManager() { |
| 59 | + // @formatter: off |
| 60 | + List<AccessDecisionVoter<? extends Object>> decisionVoters = |
| 61 | + Arrays.asList( |
| 62 | + new WebExpressionVoter(), |
| 63 | + new RoleVoter(), |
| 64 | + new AuthenticatedVoter(), |
| 65 | + new MinuteBasedVoter()); |
| 66 | + // @formatter: on |
| 67 | + return new UnanimousBased(decisionVoters); |
| 68 | + } |
| 69 | +} |
0 commit comments