![c2d65b991864dd17e4149bd2227be9f7.png](https://img-blog.csdnimg.cn/img_convert/c2d65b991864dd17e4149bd2227be9f7.png)
很多失败不是因为能力有限,而是没有坚持到底
【Spring Security:安全管理框架】
八、Thymeleaf 中 Spring Security 的使用
Spring Security可以在一些视图技术中进行控制显示效果。例如:JSP或Thymeleaf。在非前后端分离且使用Spring Boot的项目中多使用Thymeleaf作为视图展示技术。
Thymeleaf对Spring Security的支持都放在thymeleaf-extras-springsecurityX中,目前最新版本为5。所以需要在项目中添加此jar包的依赖和thymeleaf的依赖。
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在html页面中引入thymeleaf命名空间和security命名空间
![eb15e458dcb76cfbeed9e29b39baa615.png](https://img-blog.csdnimg.cn/img_convert/eb15e458dcb76cfbeed9e29b39baa615.png)
1. 获取属性
可以在html页面中通过 sec:authentication=""获取UsernamePasswordAuthenticationToken中所有getXXX的内容,包含父类中的getXXX的内容。
根据源码得出下面属性:
- name:登录账号名称
- principal:登录主体,在自定义登录逻辑中是UserDetails
- credentials:凭证
- authorities:权限和角色
- details:实际上是WebAuthenticationDetails的实例。可以获取remoteAddress(客户端ip)和sessionId(当前sessionId)
实现步骤:
① 新建demo.html
在项目resources中新建templates文件夹,在templates中新建demo.html页面