环境

springboot:2.2.5
thymeleaf-extras-springsecurity:5.x
jdk:1.8
maven:3.6.2

导入依赖

在pom.xml中导入thymeleaf和security还有thymeleaf-security整合的相关依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

<!--thymeleaf-security整合包-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

security配置

继承WebSecurityConfigurerAdapter,编写security配置
在config包下新建一个自命名的配置文件,比如SecurityConfig类,继承WebSecurityConfigurerAdapter,重写父类方法,可以配置http拦截请求、登录拦截,权限的拦截等等自定义功能,我这里简单写个demo,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.ghostwang.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;

// aop 拦截器

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//http访问权限
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人可以访问, 功能页只有对应有权限的人才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");


// 没有权限默认跳到登录页,loginPage定制登录页,没有定义的话就用它自带的
// 自定义前端传过来的账号密码的参数名,前后端要统一
http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd");

// 防止网站攻击
http.csrf().disable(); //关闭csrf

// 开启注销功能
//http.logout().deleteCookies("remove").invalidateHttpSession(true);
http.logout().logoutSuccessUrl("/");


// 开启记住我功能,本质是保存了cookie,有效期默认两周
// 自定义接收前端的记住我参数,跟前端的input标签上的name属性对应一致
http.rememberMe().rememberMeParameter("remember");
}

// 认证
// 登录密码需要加密
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

// 这些数据正常应该从数据库中取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("wangcong").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1","vip2","vip3")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1");
}
}

更多的配置信息可以点进父类的源码,其中的注释非常详细!

thymeleaf中使用security

####github官方地址

一些常用的属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 展示登录名
<div th:text="${#authentication.name}"></div>

// 使用属性获取登录名
<div sec:authentication="name">
The value of the "name" property of the authentication object should appear here.
</div>

// 条件判断,判断是否有ADMIN这个角色
<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>

// 使用属性判断是否有相应的角色(权限)
<div sec:authorize="${hasRole(#vars.expectedRole)}">
This will only be displayed if authenticated user has a role computed by the controller.
</div>

// 获取登录用户的相应权限(角色)
<div th:text="${#authentication.getAuthorities()}"></div>

更多的可以看官网或者源码获取。

登录注销小案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--登录注销-->
<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 th:text="${#authentication.name}"></span>
角色: <span th:text="${#authentication.getAuthorities()}"></span>
</a>
</div>
<div sec:authorize="${isAuthenticated()}">
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
</div>

记录一个踩过的小坑:

thymeleaf-security如果是使用4.x版本的,那么html文件中的命名空间是 xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4,如果是用的5.x的版本,html头文件申明的命名空间应该是xmlns:sec="http://www.thymeleaf.org/extras/spring-security"