SpringSecurity(安全)

在web开发中,安全第一位!过滤器,拦截器~

功能性需求:否

做网站:安全应该在什么时候考虑?设计之初!

  • 漏洞,隐私泄露~

  • 架构一旦确定~

shiro、SpringSecurity:很像~除了类不一样,名字不一样;

认证,授权(vip1,vip2,vip3)

  • 功能权限

  • 访问权限

  • 菜单权限

  • …拦截器,过滤器:大量的原生代码~兄余
    MVC-Spring—SpringBoot—框架思想

Aop:做一个配置类

简介
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是“认证”和“授权”(访问控制)。

“认证”(Authentication)

“授权”(Authorization)

这个概念是通用的,而不是只在Spring Security中存在。

参考官网:https://spring.io/projects/spring-security,查看我们自己项目中的版本,找到对应的帮助文档:[https://docs.spring.io/spring-security/site/docs/5.2.0.RELEASE/reference/htmlsingle](https://docs.spring.io/spring-security/site/docs/5.2.0.RELEASE/reference/htmlsingle)

搭建环境

  1. 创建一个有web功能的springboot项目

  2. 关闭缓存

    1. spring.thymeleaf.cache=false
  1. 导入素材

  2. 导入依赖

    1. <!--thymeleaf模板-->
    2. <dependency>
    3. <groupId>org.thymeleaf</groupId>
    4. <artifactId>thymeleaf-spring5</artifactId>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.thymeleaf.extras</groupId>
    8. <artifactId>thymeleaf-extras-java8time</artifactId>
    9. </dependency>
  1. 配置路由跳转控制

    1. @Controller
    2. public class RouterController {
    3. @RequestMapping({"/","/index"})
    4. public String index() {
    5. return "index";
    6. }
    7. @RequestMapping("/toLogin")
    8. public String toLogin() {
    9. return "views/login";
    10. }
    11. @RequestMapping("/level1/{id}")
    12. public String level1(@PathVariable("id") int id) {
    13. return "views/level1/"+id;
    14. }
    15. @RequestMapping("/level2/{id}")
    16. public String level2(@PathVariable("id") int id) {
    17. return "views/level2/"+id;
    18. }
    19. @RequestMapping("/level3/{id}")
    20. public String level3(@PathVariable("id") int id) {
    21. return "views/level3/ "+id;
    22. }
    23. }

构建Security

导入依赖

  1. <!--security-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>

完善拦截器功能

  1. //Aop: 拦截器
  2. @EnableWebSecurity
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  4. //授权
  5. //链式编程
  6. @Override
  7. protected void configure(HttpSecurity http) throws Exception {
  8. //主页所有人可以访问,功能页只有对应有权限的人才访问
  9. //请求授权的规则
  10. http.authorizeRequests()
  11. .antMatchers("/").permitAll()
  12. .antMatchers("/level1/**").hasRole("vip1")
  13. .antMatchers("/level2/**").hasRole("vip2")
  14. .antMatchers("/level3/**").hasRole("vip3");
  15. //没有权限默认会到登录页面
  16. http.formLogin();
  17. }
  18. //认证,springboot 2.1.X可以直接使用~
  19. //密码编码:PasswordEncoder
  20. //在Spring Secutiry 5.0+ 新增了很多的加密方法
  21. @Override
  22. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  23. //这些数据正常应该从数据库中读
  24. auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
  25. .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
  26. .and()
  27. .withUser("6b92d6").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
  28. .and()
  29. .withUser("dafran").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
  30. }
  31. }

权限控制和注销

导入依赖

  1. <!--security-thymeleaf整合包-->
  2. <dependency>
  3. <groupId>org.thymeleaf.extras</groupId>
  4. <artifactId>thymeleaf-extras-springsecurity4</artifactId>
  5. <version>3.0.4.RELEASE</version>
  6. </dependency>

降低SpringBoot版本为:2.0.9.RELEASE

增加注销及关闭csrf功能

  1. //防止网站工具:get,post
  2. http.csrf().disable(); //关闭csrf功能,登录失败可能存在的原因
  3. //注销,开启注销功能,跳转到首页
  4. http.logout().logoutSuccessUrl("/");

前端修改

  1. <!--如果未登录-->
  2. <div sec:authorize="!isAuthenticated()">
  3. <a class="item" th:href="@{/toLogin}">
  4. <i class="address card icon"></i> 登录
  5. </a>
  6. </div>
  7. <!--如果登录: 用户名、角色、注销-->
  8. <div sec:authorize="isAuthenticated()">
  9. <a class="item">
  10. 用户名:<span sec:authentication="name"></span>
  11. <!-- 角色:<span sec:authentication="principal.getAuthorities()"></span>-->
  12. </a>
  13. </div>
  14. <div sec:authorize="isAuthenticated()">
  15. <!--注销-->
  16. <a class="item" th:href="@{/logout}">
  17. <i class="sign-out icon"></i> 注销
  18. </a>
  19. </div>
  1. <div class="column" sec:authorize="hasRole('vip1')">
  2. <div class="ui raised segment">
  3. <div class="ui">
  4. <div class="content">
  5. <h5 class="content">Level 1</h5>
  6. <hr>
  7. <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
  8. <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
  9. <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. <div class="column" sec:authorize="hasRole('vip2')">
  15. <div class="ui raised segment">
  16. <div class="ui">
  17. <div class="content">
  18. <h5 class="content">Level 2</h5>
  19. <hr>
  20. <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
  21. <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
  22. <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
  23. </div>
  24. </div>
  25. </div>
  26. </div>
  27. <div class="column" sec:authorize="hasRole('vip3')">
  28. <div class="ui raised segment">
  29. <div class="ui">
  30. <div class="content">
  31. <h5 class="content">Level 3</h5>
  32. <hr>
  33. <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
  34. <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
  35. <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
  36. </div>
  37. </div>
  38. </div>
  39. </div>

记住我和首页定制

增加配置

  1. //开启记住我功能 cookie,默认保存两周
  2. http.rememberMe().rememberMeParameter("remember");
  3. //没有权限默认会到登录页面,定制登录页
  4. http.formLogin().loginPage("/toLogin")
  5. .usernameParameter("user").passwordParameter("pwd")
  6. .loginProcessingUrl("/login");

同时修改html

  1. <div class="ui form">
  2. <form th:action="@{/login}" method="post">
  3. <div class="field">
  4. <label>Username</label>
  5. <div class="ui left icon input">
  6. <input type="text" placeholder="Username" name="user">
  7. <i class="user icon"></i>
  8. </div>
  9. </div>
  10. <div class="field">
  11. <label>Password</label>
  12. <div class="ui left icon input">
  13. <input type="password" name="pwd">
  14. <i class="lock icon"></i>
  15. </div>
  16. </div>
  17. <div class="field">
  18. <input type="checkbox" name="remember">记住我
  19. </div>
  20. <input type="submit" class="ui blue submit button"/>
  21. </form>
  22. </div>
  1. 其中`th:action="@{/login}"``.loginPage("/login")`对应;
  2. 或者增加`.loginPage("/toLogin").loginProcessingUrl("/login")`
  3. `.usernameParameter("user").passwordParameter("pwd")``input`name属性相同