本文主要是介绍进阶SpringBoot之 SpringSecurity(3)注销及权限控制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在授权(HttpSecurity http)方法下开启注销,关闭 CSRF:
跨站请求伪造(CSRF)是一种冒充受信任用户,向服务器发送非预期请求的攻击方式
这些非预期请求可能是通过在跳转链接后的 URL 中加入恶意参数来完成
//防止网站攻击
http.csrf().disable(); //关闭csrf功能
//开启注销功能,跳转到首页
http.logout().logoutSuccessUrl("/");
pom.xml 导入 thymeleaf-extras-springsecurity5 整合包:
<!-- security-thymeleaf整合包 --><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.1.2.RELEASE</version></dependency>
index.html 头部引入 th、sec 命名空间
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
<html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
注销前端代码:
<!-- 登录注销 -->
<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 sec:authentication="name"></span>角色:<span sec:authentication="principal.authorities"></span></a></div><div sec:authorize="isAuthenticated()"><a class="item" th:href="@{/logout}"><i class="sign-out icon"></i> 注销</a></div>
</div>
身份不同,权限不同,展示页面不同
只需添加一行 <div class="column" sec:authorize="hasRole('vip1')"> 设置只有能访问 vip1 的用户才可见
<div class="ui three column stackable grid"><!--菜单根据用户的角色动态地实现--><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>
</div>
这篇关于进阶SpringBoot之 SpringSecurity(3)注销及权限控制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!