springboot与安全

SpringSecurity

使用

  • 引入依赖
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
  • 编写SpringSecurity配置类

    @EnableWebSecurity 并且extends WebSecurityConfigurerAdapter

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    @EnableWebSecurity
    public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

    //定义授权规则
    //允许所有人访问/请求
    http.authorizeRequests().antMatchers("/").permitAll()
    .antMatchers("/level/**").hasAnyRole("vip")
    .antMatchers("/level1/**").hasAnyRole("vip1");

    //开启自动配置的登录功能
    http.formLogin();
    //1、/login会进入登录页
    //2、重定向到/login/error是登录失败
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //定义认证规则
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip");


    }
    }

web页面定制

参考官方文档https://spring.io/guides/gs/securing-web/