1、SpringSecurity(安全)
1、简介
市面上存在比较有名的安全框架:Shiro,Spring Securiyt
springsecurity是一个功能强大、可高度定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
springsecurity是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring安全的真正强大在于它可以轻松地扩展以满足定制需求。
重点:Spring Security 基于 Spring框架,提供了一套Web应用安全性的完整解决方案。一般来说,Web应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。
- 用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户是否能访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
- 用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中不同用户所具有的权限是不同的。
对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security框架支持主流的认证方式,包括HTTP基本认证、HTTP表单验证、HTTP摘要认证、OpenID和LDAP等。在用户授权方面,Spring Security提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对用用中的领域对象进行细粒度的控制。
认识Spring Security
Spring Security是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是“认证”和“授权”(访问控制)
- 认证(Authentication):身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
- 授权(Authorization):授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
2、环境搭建
-
新建一个初始的springboot项目web模块,thymeleaf模块
-
导入静态资源
-
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; } }
-
测试环境
3、认证和授权
目前,我们的测试环境,是谁都可以访问的,我们使用Spring Security增加上认证和授权的功能
-
引入Spring Security模块
<!--security--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
-
编写基本 Spring Security配置类
package com.longyu.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 // 开启WebSecurity模式 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { } }
-
定制请求的授权规则
// 授权 @Override protected void configure(HttpSecurity http) throws Exception { // 首页所有人可以访问,功能也只有对应有权限的人才能访问 // 请求授权的规则 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); }
-
测试:发现除了首页都进不去了!因为我们目前没有登录角色,因为请求需要登录的角色拥有对应的权限才可以!
-
在confiure()方法中加入以下配置,开启自动配置的登录功能!
// 开启自动配置的登录功能 // /login请求来到登录页 // /login?error重定向到这里表示登录失败 http.formLogin();
-
测试:发现没有权限的时候,会跳转到登录的页面!
-
我们定义认证规则,重写protected void configure(AuthenticationManagerBuilder auth) 方法
// 认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 在内存中定义,也可以在jdbc中去拿... auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("longyu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); }
SpringSecurity中从前端传来的密码需要进行某种方式加密,
在Spring Security 5.0中新增了多种加密方式,也改变了密码的格式。
所以在这里我们使用了官方推荐的 bcrypt 加密方式。
new BCryptPasswordEncoder().encode() 来加密
-
测试,登录,每个角色只能访问自己认证下的规则!
4、权限控制和注销
-
开启自动配置的注销的功能
// 注销 开启了注销功能 http.logout();
-
我们在前端,增加一个注销的按钮
<a class="item" th:href="@{/logout}"> <i class="sign-out icon"></i> 注销 </a>
-
测试:发现注销完毕会跳到登录页面!
-
想要注销成功后,跳转到首页
// 注销成功后,来到首页 http.logout().logoutSuccessUrl("/");
-
测试:注销成功后,跳转到首页!
-
需求:
用户没有登录的时候,导航栏上只显示登录按钮,
用户登录之后,导航栏可以显示登录的用户信息及注销按钮!
还有就是,登录的用户显示对应的权限功能,比如:longyu这个用户,他只有vip2,vip3功能,name登录则只显示这两个功能,而vip1的功能菜单不显示!我们需要结合thymeleaf中的一些功能
导入thymeleaf和springsecurity结合的依赖
<!--security-Thymeleaf整合包--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.4.RELEASE</version> </dependency>
sec:authorize=“isAuthenticated()”:是否认证登录!来显示不同的页面
-
修改前端页面
导入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
修改导航栏,添加认证判断
<!--登录注销--> <div class="right menu"> <!--如果未登录--> <div sec:authorize="!isAuthenticated()"> <a class="item" th:href="@{/toLogin}"> <i class="address card icon"></i> 登录 </a> </div> <!--如果登录,用户名,注销--> <div sec:authorize="isAuthenticated()"> <a class="item"> 用户名: <span sec:authentication="principal.username"></span> 角色: <span sec:authentication="principal.authorities"></span> </a> </div> <div sec:authorize="isAuthenticated()"> <a class="item" th:href="@{/logout}"> <i class="sign-out icon"></i> 注销 </a> </div> </div>
principal.username:显示用户名
principal.authorities:显示角色的权限
-
重启测试
-
如果注销404页面,是因为它默认放置csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改成post表单提交,或者在spring security中关闭csrf功能;
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
-
我们继续将下面的角色功能块认证完成
<div> <br> <div class="ui three column stackable grid"> <!--菜单根据用户角色动态的实现--> <div class="column" sec:authorize="hasRole('vip1')"> <div class="ui raised segment"> <div class="ui"> <div class="content"> <h5 class="content">Level 1</h5> <hr> <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div> <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div> <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div> </div> </div> </div> </div> <div class="column" sec:authorize="hasRole('vip2')"> <div class="ui raised segment"> <div class="ui"> <div class="content"> <h5 class="content">Level 2</h5> <hr> <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div> <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div> <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div> </div> </div> </div> </div> <div class="column" sec:authorize="hasRole('vip3')"> <div class="ui raised segment"> <div class="ui"> <div class="content"> <h5 class="content">Level 3</h5> <hr> <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div> <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div> <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div> </div> </div> </div> </div> </div> </div>
ps:只要在页面的div中后加入对应的权限即可 sec:authorize="hasRole(‘vip1’)
-
权限控制和注销搞定!
5、记住我
就是将用户名和密码保存到网站的cookie中
-
开启记住我功能
只需要在授权功能那个方法里面添加
//记住我 http.rememberMe();
-
注销的时候,springsecurity会帮我们自动删除这个cookie
ps:默认cookie会保存14天
6、定制登录页
现在登录页面默认是spring security的, 我们需要使用自己的Login页面
-
在刚才的登录页配置后面指定loginpage
// 没有权限默认会到登录页面,需要开启登录的页面 http.formLogin().loginPage("/toLogin")
-
前端也需要指定我们自己定义的login请求
<a class="item" th:href="@{/toLogin}"> <i class="address card icon"></i> 登录 </a>
-
我们登录,要将这些信息发送到哪里,我们也需要配置,login.html配置提交请求及方式,方式必须为post:
<form th:action="@{/login}" method="post"> <div class="field"> <label>Username</label> <div class="ui left icon input"> <input type="text" placeholder="Username" name="uname"> <i class="user icon"></i> </div> </div> <div class="field"> <label>Password</label> <div class="ui left icon input"> <input type="password" name="upwd"> <i class="lock icon"></i> </div> </div> <div class="field"> <input type="checkbox" name="remember"> 记住我 </div> <input type="submit" class="ui blue submit button"/> </form>
-
处理请求,我们需要在配置类中配置用户名和密码
// 没有权限默认会到登录页面,需要开启登录的页面 http.formLogin().loginPage("/toLogin") .usernameParameter("uname") .passwordParameter("upwd") .loginProcessingUrl("/login");// 登录表单提交请求
-
在我们自己的页面配置记住我
<input type="checkbox" name="remember"> 记住我
-
后端验证处理
http.rememberMe().rememberMeParameter("remember");// 定制记住我的参数
-
测试。
// 没有权限默认会到登录页面,需要开启登录的页面 http.formLogin().loginPage("/toLogin") .usernameParameter("uname") .passwordParameter("upwd") .loginProcessingUrl("/login");// 登录表单提交请求
-
在我们自己的页面配置记住我
<input type="checkbox" name="remember"> 记住我
-
后端验证处理
http.rememberMe().rememberMeParameter("remember");// 定制记住我的参数
-
测试。