Spring Security
是针对 Spring
项目的安全框架,也是Spring Boot
底层安全模块默认的技术选型,它可以实现强大的应用安全控制,我们只需引入 spring-boot-starter-security
模块,再进行少量的配置,即可实现强大的安全管理。
Spring Security
的两个主要目标是 “认证” 和 “授权”(访问控制)。
在我们日常的应用开发当中,安全是在设计之初就需要考虑的问题,否则架构一旦确定,就需要改动大量的代码;Spring Security
提供了身份认证和权限控制的一系列功能。
以前实现这些功能,我们需要使用大量的原生代码来实现拦截器、过滤器,使代码变得冗余且安全性也难以控制。
市面上知名的安全框架:shiro
、SpringSecurity
,两者实现的功能都很相同。
常见的几个类:
Security
策略
WebSecurity
模式,
@EnableXXX 通常表示开启某个功能
更多信息参考官网:https://spring.io/projects/spring-security
下面我们来进行详细的搭建过程
选择 web
、thymeleaf
依赖
静态资源素材地址:https://www.lanzous.com/i8orrja
关闭thymeleaf缓存
application.properties
spring.thymeleaf.cache=false
controller/RouterController.java
@Controller
public class RouterController {
@RequestMapping({"/", "index","index.html"})
private String index(){return "index";}
@RequestMapping("tologin")
private String toLogin() { return "views/login"; }
@RequestMapping("/level1/{id}")
private String level1(@PathVariable("id") int id) {return "views/level1/" + id;}
@RequestMapping("/level2/{id}")
private String level2(@PathVariable("id") int id) {return "views/level2/" + id;}
@RequestMapping("/level3/{id}")
private String level3(@PathVariable("id") int id) {return "views/level3/" + id;}
}
启动项目,测试访问 http://localhost:8080/
<!--Spring Security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
config/SecurityConfig.java
继承 WebSecurityConfigurerAdapter
类,并使用 @EnableWebSecurity
注解声明
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
Alt + Insert 键 查看可以重载的一些函数
这里我们重载 configure(HttpSecurity)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
}
需求:首页所有人可以访问,功能页只有对应有权限的人才能访问
/
/level1
下的所有页面只能等级为 vip1
的才能访问/level2
下的所有页面只能等级为 vip2
的才能访问/level3
下的所有页面只能等级为 vip3
的才能访问/login,默认为SpringSecurity自带的登录页面
config/SecurityConfig.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//设置需要控制权限的url
.antMatchers("/").permitAll() //不需要身份认证的请求
.antMatchers("/level1/**").hasRole("vip1") //指定角色访问特定的请求
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限汇默认到登录页面 "/login",/login是spring security自带的一个页面
//登录成功后默认跳转到 / 路径
http.formLogin().loginPage("/login").defaultSuccessUrl("/",true);
}
}
启动项目,访问测试
重写 configure(AuthenticationManagerBuilder)
需求
模块
auth.inMemoryAuthentication().withUser()
添加认证角色信息
BcryptPasswordEncoder()
加密模块
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("xiaoming").password(new BCryptPasswordEncoder().encode("123123"))
.roles("vip1")
.and()
.withUser("laowang").password(new BCryptPasswordEncoder().encode("123123"))
.roles("vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123123"))
.roles("vip1", "vip2", "vip3");
}
使用.and()
拼接多个配置, BCryptPasswordEncoder()
为密码加密模块
结合之前整合Mybatis的笔记,配置好数据库信息。
看文档实现
在授权部分代码中添加
//注销
http.logout().logoutSuccessUrl("/"); //指定注销成功后跳转的页面
调用logout()
模块后,会自动生成一个/logout
的URL
我们在前端添加一个注销按钮,访问该URL
<a class="item" th:href="@{/logout}">
<i class="arrow circle right icon"></i>注销
</a>
点击按钮后会调转到默认的logout页面,点击确认后跳转到主页
需求如下:
在 maven官网 找到 Spring Security
对 Thymeleaf
的整合包
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
在 pom.xml
的 properties
标签中加入,否则在 html
模板中的 sec
标签不生效,原因未知。
<thymeleaf-extras-springsecurity5.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity5.version>
在index.html
文件中引用命名空间 xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
通过以下配置,实现两点需求:
定位到<div class="right menu">
标签,修改子标签内容如下
<!--未登录-->
<a sec:authorize="!isAuthenticated()" class="item" th:href="@{/login}">
<i class="address card icon"></i>登录
</a>
<a sec:authorize="isAuthenticated()" class="item">
<i class="address card icon"></i>
用户名:<span sec:authentication="name"></span>
</a>
<a sec:authorize="isAuthenticated()" class="item">
<i class="address card icon"></i>
角色:<span sec:authentication="principal.authorities"></span>
</a>
<!--已登录 -->
<a sec:authorize="isAuthenticated()" class="item" th:href="@{/logout}">
<i class="arrow circle right icon"></i>注销
</a>
附加:添加登录状态提示语
<div class="ui segment" style="text-align: center">
<h3 sec:authorize="!authenticated">Please Sign in</h3>
<h3 sec:authorize="authenticated">Welcome Sign in the system</h3>
</div>
在上面的代码当中我们使用以下几个拓展spring security的属性和方法
sec:authorize="!isAuthenticated()"
判断用户是否已认证,在前面加上!
表示取反,
sec:authentication="name"
获取用户名
未登录
登录
定位到index.html
中的 <div class="ui three column stackable grid">
标签
使用 sec:authorize="hasRole('ROLE_vip1')
中的 hasRole()
对用户身份进行判断
例如:
<!--lever 1-->
<div sec:authorize="hasRole('ROLE_vip1')" class="column">
<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>
我们可以直接在configure(HttpSecurity http)
中添加 http.rememberMe();
再重新登录,访问login页面,就能看到 remember me的选项
我们勾选上并尝试登录
登录成功后我们可以看到 spring security会自动返回一个cookie值到我们的浏览器当中,实现用户会话信息的保存。
在这之前的操作一直以来登录页面都是使用 spring security自带的登录页面,通常我们都是需要替换成自己设计的登录页面
这里我们原来配置的登录页面的路由为 /tologin
@RequestMapping("/tologin")
private String toLogin() { return "views/login"; }
我们修改 config
中的 http.formLogin()
http.formLogin()
.loginPage("/tologin") //自己设计的登录页面url
.usernameParameter("userName") //修改为自己表单中的name值:默认为 username和password
.passwordParameter("passWord")
.defaultSuccessUrl("/",true)
.loginProcessingUrl("/login"); //提交登录请求的url
rememberme的name值也可以用.rememberMeParameter()
自定义,默认为remember-me
在自己的login页面中添加 rememberme 标签
<div class="field">
<input th:text="保存会话信息" type="checkbox" name="remember-me"/>
</div>
修改表单提交的 url 为 /login
<form th:action="@{/login}" method="post">
页面效果
测试登录,登录成功,如下图所示。
http.csrf().disable()
来关闭csrf验证即可解决