一、概述
市面上存在比较有名的安全框架:Shiro,Spring Security。除了类和名字不一样,其他类似。
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。
安全框的主要主要功能就是身份认证和授权。
权限分为以下三类:
- 功能权限
- 访问权限
- 菜单权限
以前需要用拦截器和过滤器,使用大量的原生代码,冗余
一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。
用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般通过校验用户名和密码来完成认证过程。
用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
在用户认证方面,Spring Security 框架支持 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID和 LDAP 等主流的认证方式。
在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。
二、实战测试
2.1、环境搭建
-
新建一个SpringBoot项目
-
导入静态资源
-
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; } }
-
测试
2.2、Spring Security
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security
模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式 @Enablexxx开启某个功能
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
2.3、认证和授权
现在的测试环境是所有人都可以访问,使用Spring Security
增加上认证和授权的功能。
-
引入
Spring Security
模块<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
-
编写
Spring Security
配置类@EnableWebSecurity // 开启WebSecurity模式 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { } }
-
编写基础配置类
@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"); }
-
测试:除了首页都进不去了!因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以
-
在
configure()
方法中加入以下配置,开启自动配置的登录功能// 开启自动配置的登录功能 // /login 请求来到登录页 // /login?error 重定向到这里表示登录失败 http.formLogin();
-
测试:没有权限的时候,会跳转到登录的页面
-
查看刚才登录页的注释信息,我们可以定义认证规则,重写
configure(AuthenticationManagerBuilder auth)
方法//定义认证规则 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception{ //在内存中定义,也可以在jdbc中去拿.... auth.inMemoryAuthentication() .withUser("zhang").password("123456").roles("vip2","vip3") .and() .withUser("root").password("123456").roles("vip1","vip2","vip3") .and() .withUser("haha").password("123456").roles("vip1","vip2"); }
-
测试:可以使用这些账号登录进行测试,发现会报错
-
原因:我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码
// 认证,SpringBoot2.1.x是可以直接使用 // 密码编码:PasswordEncoder // 在Spring 5.0+,新增了很多加密方法 //spring security 官方推荐的是使用bcrypt加密方式 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 这些用户名密码正常应该从数据库中读 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("zhang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3") .and() .withUser("haha").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); }
-
测试:登录成功,并且每个角色只能访问自己认证下的规则
2.4、权限控制和注销
-
开启自动配置的注销的功能
//定制请求的授权规则 @Override protected void configure(HttpSecurity http) throws Exception { //开启自动配置的注销的功能 // /logout 注销请求 http.logout(); }
-
我们在前端,增加一个注销的按钮,
index.html
导航栏中<a class="item" th:href="@{/logout}"> <i class="address card icon"></i> 注销 </a>
-
测试:登录成功后点击注销,发现注销完毕会跳转到登录页面
-
注销成功后,跳转到首页
// .logoutSuccessUrl("/"); 注销成功来到首页 http.logout().logoutSuccessUrl("/");
-
测试:注销完毕后,可以跳转到首页
-
用户没有登录的时候,导航栏上只显示登录按钮;用户登录之后,导航栏可以显示登录的用户信息及注销按钮。而且只显示对应权限的菜单
需要结合thymeleaf中的一些功能sec:authorize="isAuthenticated()":是否认证登录
,来显示不同的页面导入依赖
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleafextras-springsecurity4 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency>
-
修改前端页面
<!-- 导入命名空间 --> xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5" <!--登录注销,增加登录判断--> <div class="right menu"> <!--如果未登录--> <div sec:authorize="!isAuthenticated()"> <a class="item" th:href="@{/login}"> <i class="address card icon"></i> 登录 </a> </div> <!--如果已登录--> <div sec:authorize="isAuthenticated()"> <a class="item"> <i class="address card icon"></i> 用户名: <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="address card icon"></i> 注销 </a> </div> </div>
-
如果注销404,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能,在配置类添加:
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout 请求 http.logout().logoutSuccessUrl("/");
-
角色功能块认证
<!-- sec:authorize="hasRole('vip1')" --> <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>
2.5、记住我
即记住密码的功能
-
开启记住我功能
//定制请求的授权规则 @Override protected void configure(HttpSecurity http) throws Exception { //。。。。。。。。。。。 //记住我 http.rememberMe(); }
-
再次启动项目测试,发现登录页多了一个记住我功能,登录之后关闭浏览器,然后重新打开浏览器访问,发现用户依旧存在
-
登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以
免登录了。如果点击注销,则会删除这个cookie
2.6、定制登录页
现在这个登录页面都是spring security 默认的,也可以使用自己定义的
-
修改配置类
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="username"> <i class="user icon"></i> </div> </div> <div class="field"> <label>Password</label> <div class="ui left icon input"> <input type="password" name="password"> <i class="lock icon"></i> </div> </div> <input type="submit" class="ui blue submit button"/> </form>
-
查看 formLogin() 方法的源码,配置接收登录的用户名和密码的参数
http.formLogin() .usernameParameter("username") .passwordParameter("password") .loginPage("/toLogin") .loginProcessingUrl("/login"); // 登陆表单提交请求
-
在登录页增加记住我的多选框
<input type="checkbox" name="remember"> 记住我
-
后端验证处理
//定制记住我的参数! http.rememberMe().rememberMeParameter("remember");