springboot与Security

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

security配置文件

package cn.onbe.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter{

    private static final Logger logger = LoggerFactory.getLogger(MySecurityConfig.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");

        // 定制请求授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level/1").hasRole("vip1")
        .antMatchers("/level/2").hasRole("vip2")
        .antMatchers("/level/3").hasRole("vip3")
        .antMatchers("/level/4").hasRole("vip4");
        // 开启自动配置的登陆功能
        http.formLogin();
        http.logout().logoutSuccessUrl("/");
        http.rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
        .and()
        .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
        .and()
        .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip3");
    }
}