当前位置:   article > 正文

SpringBoot中Spring Security 的使用_spring boot security

spring boot security

1.Spring Security 的介绍

     Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

     Spring Security对Web安全性的支持大量地依赖于Servlet过滤器。这些过滤器拦截进入请求,并且在应用程序处理该请求之前进行某些安全处理。 Spring Security提供有若干个过滤器,它们能够拦截Servlet请求,并将这些请求转给认证和访问决策管理器处理,从而增强安全性。根据自己的需要,可以使用适当的过滤器来保护自己的应用程序。

    它的更新日志:

 2.在SpringBoot中的使用

(1)首先是环境的配置,版本的使用

springboot的版本:

然后添加的是Spring Security的maven的配置 

 

 (2)前端网页资源

 其中各个level中的页面是要带有某种权力才可以去访问到的,比如说是vip1只能访问到level1中的1,2,3界面,后面会进行相关的配置(相关的页面资源在文末有相关baiduyun链接)

(3)视图控制器来进行页面的跳转

  1. package com.csg.springbootsecurity.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. public class ViewController {
  7. @RequestMapping({"/","/index"})
  8. public String index()
  9. {
  10. return "index";
  11. }
  12. @RequestMapping("/tologin")
  13. public String login()
  14. {
  15. return "views/login";
  16. }
  17. @RequestMapping("/level1/{id}")
  18. public String level1(@PathVariable("id") int id)
  19. {
  20. return "views/level1/"+id;
  21. }
  22. @RequestMapping("/level2/{id}")
  23. public String level2(@PathVariable("id") int id)
  24. {
  25. return "views/level2/"+id;
  26. }
  27. @RequestMapping("/level3/{id}")
  28. public String level3(@PathVariable("id") int id)
  29. {
  30. return "views/level3/"+id;
  31. }
  32. }

(4)再来到的是Spring Security在springboot中的配置类

 

  1. package com.csg.springbootsecurity.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  9. @EnableWebSecurity
  10. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  11. @Override
  12. protected void configure(HttpSecurity http) throws Exception {
  13. http.authorizeRequests().antMatchers("/").permitAll()
  14. .antMatchers("/level1/**").hasRole("vip1")
  15. .antMatchers("/level2/**").hasRole("vip2")
  16. .antMatchers("/level3/**").hasRole("vip3");
  17. http.formLogin().loginPage("/tologin");//开启登录功能跳转的是自带的界面,发送的是/tologin请求来到的是login的界面,那么登录的表单和这里都是登录界面的请求
  18. http.logout().logoutSuccessUrl("/");//注销的功能
  19. http.csrf().disable();
  20. http.rememberMe().rememberMeParameter("remember");
  21. }
  22. @Override
  23. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  24. auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
  25. .withUser("csh").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
  26. .and()
  27. .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
  28. .and()
  29. .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
  30. }
  31. }
@EnableWebSecurity:开启安全配置,同时标记类为配置类

 

WebSecurityConfigurerAdapte:同时配置类要继承的是web安全配置适配器,重写当中的方法,进行自己的安全配置。

重写方法的介绍:

(1)

WebSecurityConfigurerAdapter中的原码:

  1. protected void configure(HttpSecurity http) throws Exception {
  2. this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
  3. http.authorizeRequests((requests) -> {
  4. ((AuthorizedUrl)requests.anyRequest()).authenticated();
  5. });
  6. http.formLogin();
  7. http.httpBasic();
  8. }

在我们重写的时候

http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("vip1")

anMatchers(这里要写的是我们访问的url)而后面是permitAll的话是允许全部的访问,而后接hasRole是要带某种权力才能访问得到

登录功能的实现:

http.formLogin().loginPage("/tologin");//开启登录功能跳转的是自带的界面,如果加上loginPage的话发送一个请求,这里发送的是/tologin请求来到的是login的界面
http.formLogin()

是来默认开启登录的功能,没有配置接loginPage("/tologin")的话是默认跳转的是自带的登录界面

 我这里是跳转到了自己的登录界面

记住我功能的实现:

http.rememberMe().rememberMeParameter("remember");

在前端页面中是:

 功能是保存好用户的一个cookie

 

(2)

重写的方法:

  1. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  2. this.disableLocalConfigureAuthenticationBldr = true;
  3. }
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("csh").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")

withUser(账户名)  这里注意的是password要进行的是加密的密码,这里我采用的是BCryptPasswordEncoder().encode("123456"),同时后面的roles是代表的权限

(5)前端视图的过滤(不同权限不同视图)

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org"
  3. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  7. <title>首页</title>
  8. <!--semantic-ui-->
  9. <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
  10. <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
  11. </head>
  12. <body>
  13. <!--主容器-->
  14. <div class="ui container">
  15. <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
  16. <div class="ui secondary menu">
  17. <a class="item" th:href="@{/index}">首页</a>
  18. <!--已经登录了-->
  19. <!--登录注销-->
  20. <div class="right menu" >
  21. <!--如果没有登陆-->
  22. <div sec:authorize="!isAuthenticated()">
  23. <a class="item" th:href="@{/tologin}">
  24. <i class="address card icon"></i> 登录
  25. </a>
  26. </div>
  27. <div sec:authorize="isAuthenticated()">
  28. <a class="item">
  29. <i class="address card icon"></i>
  30. 用户名: <span sec:authentication="principal.username">
  31. </span>
  32. 角色:<span sec:authentication="principal.authorities">
  33. </span>
  34. </a>
  35. </div>
  36. <!--已登录
  37. <a th:href="@{/usr/toUserCenter}">
  38. <i class="address card icon"></i> admin
  39. </a>
  40. -->
  41. <div sec:authorize="isAuthenticated()">
  42. <a class="item" th:href="@{/logout}">
  43. <i class="address card icon"></i> 注销
  44. </a>
  45. </div>
  46. </div>
  47. </div>
  48. </div>
  49. <div class="ui segment" style="text-align: center">
  50. <h3>Spring Security Study by 秦疆</h3>
  51. </div>
  52. <div>
  53. <br>
  54. <div class="ui three column stackable grid">
  55. <div class="column" sec:authorize="hasRole('vip1')">
  56. <div class="ui raised segment">
  57. <div class="ui">
  58. <div class="content">
  59. <h5 class="content">Level 1</h5>
  60. <hr>
  61. <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
  62. <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
  63. <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
  64. </div>
  65. </div>
  66. </div>
  67. </div>
  68. <div class="column" sec:authorize="hasRole('vip2')">
  69. <div class="ui raised segment">
  70. <div class="ui">
  71. <div class="content">
  72. <h5 class="content">Level 2</h5>
  73. <hr>
  74. <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
  75. <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
  76. <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. <div class="column" sec:authorize="hasRole('vip3')">
  82. <div class="ui raised segment">
  83. <div class="ui">
  84. <div class="content">
  85. <h5 class="content">Level 3</h5>
  86. <hr>
  87. <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
  88. <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
  89. <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
  90. </div>
  91. </div>
  92. </div>
  93. </div>
  94. </div>
  95. </div>
  96. </div>
  97. <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
  98. <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
  99. </body>
  100. </html>

加上两个命名空间:

xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">

(3)成果界面展示

初始界面: 

登录界面:

登录csh账户:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53896
推荐阅读
相关标签
  

闽ICP备14008679号