0


SpringBoot之SpringSecurity(安全)

SpringSecurity(安全)

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

记住几个类:

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

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

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

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

实验环境搭建

  1. 新建一个项目> 这里记得要选择thymeleaf
  2. 导入静态资源- 静态资源获取:https://gitee.com/ENNRIAAA/spring-security-material![image-20220312193101453](https://img-blog.csdnimg.cn/img_convert/ab67824f35f1c4d7877cf407185b4854.png)
  3. 创建路由RouterController跳转测试静态资源是否能够访问@ControllerpublicclassRouterController{@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;}}
  4. 运行项目进行测试

认证和授权

  1. 导入依赖<!-- security--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
  2. 编写SecurityConfig@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//授权@Overrideprotectedvoidconfigure(HttpSecurity http)throws Exception {//首页所有人可以访问,功能页只有对应有权限的人才能访问 http.authorizeHttpRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");//没有权限会默认到登录页,需要开启登录的页面///login http.formLogin();//防止网站攻击: get,post http.csrf().disable();//关闭csrf功能,登出失败可能存在的原因 //注销,开启了注销功能,跳到首页 http.logout().logoutSuccessUrl("/");}//认证 //密码编码:PasswordEncoder @Overrideprotectedvoidconfigure(AuthenticationManagerBuilder auth)throws Exception {//这些数据正常应该从数据库中读 auth.inMemoryAuthentication().passwordEncoder(newBCryptPasswordEncoder()).withUser("lzj").password(newBCryptPasswordEncoder().encode("123456")).roles("vip2","vip3").and().withUser("root").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("guest").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1");}}
  3. 测试

注销和权限控制

  1. 导入依赖<!-- security-thymeleaf整合包--><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version></dependency>
  2. 注入命名空间xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
  3. 修改登录和注销按钮> 实现用户未登录时只显示登录,用户登录后显示用户名、角色和注销<!--登录注销--><divclass="right menu"><!--如果未登录--><divsec:authorize="!isAuthenticated()"><aclass="item"th:href="@{/toLogin}"><iclass="address card icon"></i> 登录 </a></div><!-- 如果登录:用户名,注销--><divsec:authorize="isAuthenticated()"><aclass="item"> 用户名:<spansec:authentication="name"></span> 角色:<spansec:authentication="authorities"></span></a></div><divsec:authorize="isAuthenticated()"><aclass="item"th:href="@{/logout}"><iclass="sign-out icon"></i> 注销 </a></div><!--已登录 <a th:href="@{/usr/toUserCenter}"> <i class="address card icon"></i> admin </a> --></div>
  4. 修改用户的权限显示<!-- 菜单根据用户的角色动态实现--><divclass="column"sec:authorize="hasRole('vip1')"><divclass="ui raised segment"><divclass="ui"><divclass="content"><h5class="content">Level 1</h5><hr><div><ath:href="@{/level1/1}"><iclass="bullhorn icon"></i> Level-1-1</a></div><div><ath:href="@{/level1/2}"><iclass="bullhorn icon"></i> Level-1-2</a></div><div><ath:href="@{/level1/3}"><iclass="bullhorn icon"></i> Level-1-3</a></div></div></div></div></div><divclass="column"sec:authorize="hasRole('vip2')"><divclass="ui raised segment"><divclass="ui"><divclass="content"><h5class="content">Level 2</h5><hr><div><ath:href="@{/level2/1}"><iclass="bullhorn icon"></i> Level-2-1</a></div><div><ath:href="@{/level2/2}"><iclass="bullhorn icon"></i> Level-2-2</a></div><div><ath:href="@{/level2/3}"><iclass="bullhorn icon"></i> Level-2-3</a></div></div></div></div></div><divclass="column"sec:authorize="hasRole('vip3')"><divclass="ui raised segment"><divclass="ui"><divclass="content"><h5class="content">Level 3</h5><hr><div><ath:href="@{/level3/1}"><iclass="bullhorn icon"></i> Level-3-1</a></div><div><ath:href="@{/level3/2}"><iclass="bullhorn icon"></i> Level-3-2</a></div><div><ath:href="@{/level3/3}"><iclass="bullhorn icon"></i> Level-3-3</a></div></div></div></div></div>
  5. 测试

记住我和首页定制

可以使用我们自己的登录页登录

  1. 编写SecurityConfig@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//授权@Overrideprotectedvoidconfigure(HttpSecurity http)throws Exception {//首页所有人可以访问,功能页只有对应有权限的人才能访问 http.authorizeHttpRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");//没有权限会默认到登录页,需要开启登录的页面///login //定制根页面,user为表单中username的name,pwd为表单中password的name //loginProcessingUrl为表单跳转路径,若无这个,则跳转路径为toLogin http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");//防止网站攻击: get,post http.csrf().disable();//关闭csrf功能,登出失败可能存在的原因 //注销,开启了注销功能,跳到首页 http.logout().logoutSuccessUrl("/");//开启记住我功能 cookie 默认保存时间14天 //自定义接收前端参数,remember为表单中的名字 http.rememberMe().rememberMeParameter("remember");}//认证 //密码编码:PasswordEncoder @Overrideprotectedvoidconfigure(AuthenticationManagerBuilder auth)throws Exception {//这些数据正常应该从数据库中读 auth.inMemoryAuthentication().passwordEncoder(newBCryptPasswordEncoder()).withUser("lzj").password(newBCryptPasswordEncoder().encode("123456")).roles("vip2","vip3").and().withUser("root").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("guest").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1");}}
  2. 修改登录页面表单<formth:action="@{/login}"method="post"><divclass="field"><label>Username</label><divclass="ui left icon input"><inputtype="text"placeholder="Username"name="user"><iclass="user icon"></i></div></div><divclass="field"><label>Password</label><divclass="ui left icon input"><inputtype="password"name="pwd"><iclass="lock icon"></i></div></div><divclass="field"><inputtype="checkbox"name="remember">记住我 </div><inputtype="submit"class="ui blue submit button"/></form>
  3. 测试 input type=“password” name=“pwd”> 记住我 <input type="submit" class="ui blue submit button"/> ```
  4. 测试
标签: spring boot 安全 java

本文转载自: https://blog.csdn.net/qq_49137582/article/details/123525178
版权归原作者 爱学习的大雄 所有, 如有侵权,请联系我们删除。

“SpringBoot之SpringSecurity(安全)”的评论:

还没有评论