Spring Security

151 阅读2分钟

Spring Security

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型。它可以实现强大的WEB安全控制。

它的两个主要目标是:认证和授权。

第一个Spring Security程序

需求

  • 根据用户等级(vip1, vip2, vip3, vip123),只能进入对应页面
  • 未登录页面的右上角显示登陆按钮,成功登陆则显示用户名和注销按钮
  • 实现注销然后转入首页

页面的结构

(1)引入依赖

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

(2)继承WebSecurityConfigurerAdapter类来自定义Security策略

@EnableWebSecurity  //开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {  //自定义Security策略
    /*
        定制请求的授权规则:
            所有人可以访问首页
            对应页面只要对应级别才可进入
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
            antMatchers("/").permitAll()表示所有人都可访问首页
            .antMatchers("/level1/**").hasRole("vip1")表示只有
            vip1角色才能访问level1文件夹下的所有页面
         */
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //若认证失败则会跳转到 /login?error,没有认证则会重定向到login页面
        http.formLogin();
        //开启注销功能
        //它通过注销 HTTP session来实现功能,若注销成功会转到首页
        http.logout().logoutSuccessUrl("/");
    }

    @Override       //定义认证规则
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*
            可以通过jdbcAuthentication方法从jdbc获取,
            也可以从内存中获取
            此外springboot 2.2.0以上要求我们对密码进行加密
            spring security 官方推荐使用bcrypt加密方式。
         */
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("vip1").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
                .and()
                .withUser("vip2").password(new BCryptPasswordEncoder().encode("123")).roles("vip2")
                .and()
                .withUser("vip3").password(new BCryptPasswordEncoder().encode("123")).roles("vip3")
                .and()
                .withUser("vip123").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3");
    }
}

显示效果

(1)未登录页面

(2)此时点开任意一个模块都会引入登陆页面

(3)登陆完后此账号只能进入level3模块的页面,无法进入其他页面

(5)点击注销即可返回首页