SpringSecurity安全管理


SpringSecurity安全管理

介绍

SpringSecurity是spring的一个生态圈,用于安全管理,其核心就是一组过滤链,启动项目后将会自动配置。其核心就是Basic Authentication Filter 用来认证用户的身份。

SpringSecurity的核心功能主要有

  • Authentication认证(你是谁)
  • Authorization授权(你能干什么)
  • 攻击防护(防止身份伪造)

使用

  1. 创建一个springboot项目,勾选web功能

  2. 添加依赖SpringSecurity

    
    
        org.thymeleaf.extras
        thymeleaf-extras-springsecurity4
        3.0.4.RELEASE
    
    
    
    	org.springframework.boot
        spring-boot-starter-security
    
    
    
        org.thymeleaf.extras
        thymeleaf-extras-java8time
    
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
  3. 在application.yaml中配置mvc视图解析器

    spring:
      thymeleaf:
        cache: false
      mvc:
        view:
          suffix: .html
          prefix: classpath:/templates/
    # mvc视图解析器
    
  4. 在resources文件夹下编写html

  5. views/level1/1.html/(2.html-3.html)

    
    
    
        
        Title
    
    
        

    one-1


  6. views/level2/1.html/(2.html-3.html)

    
    
    
        
        Title
    
    
        

    two-1


  7. views/level3/1.html/(2.html-3.html)

    
    
    
        
        Title
    
    
        

    three-1


  8. 首页index.html

    
    
    
        
        Title
        
    
    
    
        

    首页

    lenel1


    one-1 one-2 one-3

    lenel2


    two-1 two-2 two-3

    lenel3


    three-1 three-2 three-3
  9. 登入页login.html

    
    
    
        Spring Security
        
    
    
    
    登 录
    用户名:
    密    码:
  10. controller实现视图跳转

    package com.sheep.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class RouterController{
    
        /*
         * 首页
         * */
        @RequestMapping({"/","/index","index.html"})
        public String index(){
            return "index";
        }
        /*
         * 登入页
         * */
        @RequestMapping("/toLogin")
        public String toLogin(){
            return "views/login";
        }
        /*
        * VIP1
        * */
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") int id){
            return "views/level1/"+id;
        }
        /*
         * VIP2
         * */
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") int id){
            return "views/level2/"+id;
        }
        /*
         * VIP3
         * */
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") int id){
            return "views/level1/"+id;
        }
    }
    
  11. 自定义Security策略

    注解及类作用:

    • @EnableWebSecurity:开启WebSecurituy模式
    • WebSecurityConfigurerAdapter:自定义Securituy
    • HttpSecurity:拦截授权
    • AuthenticationManagerBuilder:自定义认证
    package com.sheep.config;
    
    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 SecurityConfig extends WebSecurityConfigurerAdapter {
        /*授权*/
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //首页所有人可以访问,功能页只有对应有权限的人才能访问(所有人可以访问/,vip1的用户可以访问/level1/**,vip2的用户可以访问/level2/**,vip3的用户可以访问/level3/**)
            http.authorizeRequests().antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
            // 没有权限会默认跳到登入页面,需要开启登入的页面
            http.formLogin().loginPage("/toLogin");
            //注销,注销成功了跳到首页
            http.logout().logoutSuccessUrl("/");
            //开启记住我功能
            http.rememberMe();
            //防止网站工具(在get传输是通过明文传输的因此可能受到攻击):get,post
            http.csrf().disable();//关闭csrf功能
        }
    
        /*
        * 认证:
        *   内存认证
        *   数据库认证
        * 使用内存认证时:要设置密码编码,对密码进行加密(为了防止通过反编译拿到数据密码)
        * 在Spring Secutiry 中提供了很多加密方法
        * */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //内存认证(模仿数据库),通过.passwordEncoder(new BCryptPasswordEncoder())加密
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("sheep").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                    .and()
                    .withUser("root2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
        }
    }
    
  12. 测试