SpringSecurity



Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。


环境搭建


1)导入Thymeleaf模块

2)导入静态资源

3)controller跳转

@Controller
public class RouterController {

    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/tologin")
    public String toLogin(){
        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "views/level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "views/level2/"+id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "views/level3/"+id;
    }

}


用户认证和授权


记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证”(Authentication) 和 “授权”(Authorization)


1)引入 spring-boot-starter-security 模块


   org.springframework.boot
   spring-boot-starter-security


2)编写 Spring Security 配置类

参考官网:https://spring.io/projects/spring-security

SecurityConfig:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页只有对应的用户才能访问
        //在内存中定义,也可以在jdbc中去拿....
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页面
        http.formLogin();

        //开启注销功能,注销后跳到首页并且移除cookie和session
        // .logoutSuccessUrl("/"); 注销成功来到首页
        http.logout().deleteCookies("remove").invalidateHttpSession(false).logoutUrl("/");
    }



    //认证
    //在spring security5.0+中 新增了很多的加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常情况下在数据库里读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kaka").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("haha").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

权限控制


我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如kuangshen这个用户,它只有 vip2,vip3功能,那么登录则只显示这两个功能,而vip1的功能菜单不显示.


  • 我们需要结合thymeleaf中的一些功能

  • sec:authorize="isAuthenticated()":是否认证登录!来显示不同的页面

  • 导入thymeleaf和springboot整合的包:



    org.thymeleaf.extras
    thymeleaf-extras-springsecurity5
    3.0.4.RELEASE



  • 修改前端页面如下:
导入命名空间:  
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"



  • 如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;


记住我功能


实现记住我的功能,默认保存两个星期