SpringSecurity[6]-Thymeleaf中Spring Security的使用/退出登录/Spring Security中CSRF

上一篇:SpringSecurity[5]-基于表达式的访问控制/基于注解的访问控制/Remember Me功能实现

链接:SpringSecurity[4]-访问控制url匹配/内置访问控制方法介绍/角色权限判断_豆虫儿的博客-CSDN博客

十一、基于表达式的访问控制

十四、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>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在html页面中引入thymeleaf命名空间和security命名空间

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">

1.获取属性

可以在html页面中通过 sec:authentication=""获取UsernamePasswordAuthenticationToken中所有getXXX的内容,包含父类中的getXXX的内容。

根据源码得出下面属性:

  • l name:登录账号名称
  • l principal:登录主体,在自定义登录逻辑中是UserDetails
  • l credentials:凭证
  • l authorities:权限和角色
  • l details:实际上是WebAuthenticationDetails的实例。可以获取remoteAddress(客户端ip)和sessionId(当 前sessionId)

1.1实现步骤:

1.1.1新建demo.html

在项目resources中新建templates文件夹,在templates中新建demo.html页面

 

1.1.2编写demo.html

在demo.html中编写下面内容,测试获取到的值

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    登录账号:<span sec:authentication="name">123</span><br/>
    登录账号:<span sec:authentication="principal.username">456</span><br/>
    凭证:<span sec:authentication="credentials">456</span><br/>
    权限和角色:<span sec:authentication="authorities">456</span><br/>
    客户端地址:<span sec:authentication="details.remoteAddress">456</span><br/>
    sessionId:<span sec:authentication="details.sessionId">456</span><br/>
</body>
</html>  

1.1.3编写控制器

thymeleaf页面需要控制转发,在控制器类中编写下面方法

@RequestMapping("/demo")
public String demo(){
    return "demo";
}

2.权限判断

在html页面中可以使用sec:authorize=”表达式”进行权限控制,判断是否显示某些内容。表达式的内容和access(表达式)的用法相同。如果用户具有指定的权限,则显示对应的内容;如果表达式不成立,则不显示对应的元素。

2.1不同权限的用户显示不同的按钮

2.1.1设置用户角色和权限

设定用户具有admin,/insert,/delete权限ROLE_abc角色。

return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_abc,/insert,/delete"));

2.1.2控制页面显示效果

在页面中根据用户权限和角色判断页面中显示的内容

通过权限判断:
<button sec:authorize="hasAuthority('/insert')">新增</button>
<button sec:authorize="hasAuthority('/delete')">删除</button>
<button sec:authorize="hasAuthority('/update')">修改</button>
<button sec:authorize="hasAuthority('/select')">查看</button>
<br/>
通过角色判断:
<button sec:authorize="hasRole('abc')">新增</button>
<button sec:authorize="hasRole('abc')">删除</button>
<button sec:authorize="hasRole('abc')">修改</button>
<button sec:authorize="hasRole('abc')">查看</button>

十五、退出登录

用户只需要向Spring Security项目中发送/logout退出请求即可。

1.退出实现

实现退出非常简单,只要在页面中添加/logout的超链接即可。

<a href="/logout">退出登录

为了实现更好的效果,通常添加退出的配置。默认的退出url为/logout,退出成功后跳转到/login?logout

 

如果不希望使用默认值,可以通过下面的方法进行修改。

http.logout()     
  .logoutUrl(**"/logout"**)   
  .logoutSuccessUrl(**"/login.html"**);

2.logout其他常用配置源码解读

2.1.addLogoutHandler(LogoutHandler)

默认是contextLogoutHandler

 

默认实例内容

 

2.2clearAuthentication(boolean)

是否清除认证状态,默认为true

 

2.3invalidateHttpSession(boolean)

是否销毁HttpSession对象,默认为true

 

2.4logoutSuccessHandler(LogoutSuccessHandler)

退出成功处理器。

 

也可以自己进行定义退出成功处理器。只要实现了LogoutSuccessHandler接口。与之前讲解的登录成功处理器和登录失败处理器极其类似。

十六、Spring Security中CSRF

从刚开始学习Spring Security时,在配置类中一直存在这样一行代码:http.csrf().disable();如果没有这行代码导致用户无法被认证。这行代码的含义是:关闭csrf防护。

1.什么是CSRF

CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack” 或者Session Riding。通过伪造用户请求访问受信任站点的非法请求访问。

跨域:只要网络协议,ip地址,端口中任何一个不相同就是跨域请求。

客户端与服务进行交互时,由于http协议本身是无状态协议,所以引入了cookie进行记录客户端身份。在cookie中会存放session id用来识别客户端身份的。在跨域的情况下,session id可能被第三方恶意劫持,通过这个session id向服务端发起请求时,服务端会认为这个请求是合法的,可能发生很多意想不到的事情。

2.Spring Security中CSRF

从Spring Security4开始CSRF防护默认开启。默认会拦截请求。进行CSRF处理。CSRF为了保证不是其他第三方网站访问,要求访问时携带参数名为_csrf值为token(token在服务端产生)的内容,如果token和服务端的token匹配成功,则正常访问。

2.1实现步骤

2.1.1 编写控制器方法

编写控制器方法,跳转到templates中login.html页面。

@GetMapping("/showLogin")
public String showLogin() {
    return "login";
}

2.1.2新建login.html

在项目resources下新建templates文件夹,并在文件夹中新建login.html页面。红色部分是必须存在的否则无法正常登录。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action = "/login" method="post">
    <input type="hidden" th:value="${_csrf.token}" name="_csrf" th:if="${_csrf}"/>
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录"/>
</form>
</body>
</html>     

2.1.3修改配置类

在配置类中注释掉CSRF防护失效

//关闭csrf防护
//http.csrf().disable();

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Thymeleaf - Spring Security integration modules [Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Status This is a thymeleaf extras module, not a part of the Thymeleaf core (and as such following its own versioning schema), but fully supported by the Thymeleaf team. This repository contains two projects: thymeleaf-extras-springsecurity3 for integration with Spring Security 3.x thymeleaf-extras-springsecurity4 for integration with Spring Security 4.x Current versions: Version 3.0.2.RELEASE - for Thymeleaf 3.0 (requires Thymeleaf 3.0.3+) Version 2.1.3.RELEASE - for Thymeleaf 2.1 (requires Thymeleaf 2.1.2+) License This software is licensed under the [Apache License 2.0] (http://www.apache.org/licenses/LICENSE-2.0.html). Requirements (3.0.x) Thymeleaf 3.0.0+ Spring Framework version 3.0.x to 4.3.x Spring Security version 3.0.x to 4.2.x Web environment (Spring Security integration cannot work offline) Maven info groupId: org.thymeleaf.extras artifactId: Spring Security 3 integration package: thymeleaf-extras-springsecurity3 Spring Security 4 integration package: thymeleaf-extras-springsecurity4 Distribution packages Distribution packages (binaries + sources + javadoc) can be downloaded from SourceForge. Features This module provides a new dialect called org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect or org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect (depending on the Spring Security version), with default prefix sec. It includes: New expression utility objects: #authentication representing the Spring Security authentication object (an object implementing the org.springframework.security.core.Authentication interface). #authorization: a expression utility object with methods for checking authorization based on expressions, URLs and Access Control Lists. New attributes: sec:authentication="prop" outputs a prop property of the authentication object, similar to the Spring Secu

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值