一、需要的组件支持:

新版本这里的组件有些问题:

https://blog.csdn.net/qq_36488647/article/details/104532754
https://blog.csdn.net/YzVermicelli/article/details/106417610

然后我这里就是需要降低下一个版本,Maven依赖就不会爆红了【SpringBoot2.3.4版本】

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>

Security本体的组件:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>

Web支持 + Thymeleaf模板引擎:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

二、属性获取

然后要使用的模板目录内的页面文件需要导入Thyemleaf + Security的约束

注意一定是使用这个约束地址,新版本的地址反而无效了。。。

<html lang="en"xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

我们可以获取的用户信息:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Main-Page</title>
</head>
<body>
<h3>This is main page</h3> <p>登录账号 <span sec:authentication="name"></span></p>
<p>登录账号 <span sec:authentication="principal.username"></span></p>
<p>凭证 <span sec:authentication="credentials"></span></p>
<p>权限角色集合 <span sec:authentication="authorities"></span></p>
<p>IP地址 <span sec:authentication="details.remoteAddress"></span></p>
<p>会话ID <span sec:authentication="details.sessionId"></span></p>

</body>
</html>

访问查看:

三、权限判断:

现在我在用户权限赋予中增加角色和权限:

package cn.zeal4j.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-Tutorial
* @create 2020 09 27 21:57
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService { @Autowired
private PasswordEncoder passwordEncoder; @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 1、通过提供的用户名参数访问数据库,查询记录返回过来,如果记录不存在则抛出异常
// username = "admin";
if (!"admin".equals(username)) throw new UsernameNotFoundException("用户名不存在"); // 2、查询出来的凭证是被加密了的,这里是模拟查询的密码
String encode = passwordEncoder.encode("123456"); // 权限不可以为空,所以需要这么一个工具方法简单实现
return new User(username, encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_vip-01,ROLE_A,ROLE_B,ROLE_C,/create,/update,/delete"));
}
}

在页面中的权限控制案例:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Main-Page</title>
<style type="text/css">
h3, p {
text-align: center;
}
</style>
</head>
<body>
<h3>This is main page</h3> <p>登录账号 <span sec:authentication="name"></span></p>
<p>登录账号 <span sec:authentication="principal.username"></span></p>
<p>凭证 <span sec:authentication="credentials"></span></p>
<p>权限角色集合 <span sec:authentication="authorities"></span></p>
<p>IP地址 <span sec:authentication="details.remoteAddress"></span></p>
<p>会话ID <span sec:authentication="details.sessionId"></span></p> <h3>权限控制展示</h3>
<p> <button sec:authorize="hasRole('A')" >角色A</button> </p>
<p> <button sec:authorize="hasRole('B')" >角色B</button> </p>
<p> <button sec:authorize="hasRole('C')" >角色C</button> </p>
<p> <button sec:authorize="hasRole('D')" >角色D</button> </p> <p> <button sec:authorize="hasAuthority('/create')" >创建权限</button> </p>
<p> <button sec:authorize="hasAuthority('/update')" >更新权限</button> </p>
<p> <button sec:authorize="hasAuthority('/delete')" >删除权限</button> </p>
<p> <button sec:authorize="hasAuthority('/select')" >查询权限</button> </p>

</body>
</html>

访问查看:

可以看到角色D和SELECT权限都没有,Security对应也不会显示这些按钮

四、退出功能:

Security默认提供了Logout退出控制

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Project-Index</title>
</head>
<body>
<h1>Hello Spring-Security !!!</h1>
<a href="/logout">click to logout</a>
</body>
</html>

点击会自动重定向到登录页面来,并且会有一个logout参数值在地址中:

如果不希望附带这个参数,则需要配置退出的处理:

package cn.zeal4j.configuration;

import cn.zeal4j.handler.CustomAccessDeniedHandler;
import cn.zeal4j.handler.FarsAuthenticationFailureHandler;
import cn.zeal4j.handler.FarsAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import javax.sql.DataSource; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-Tutorial
* @create 2020 09 27 21:55
*/
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired
private AccessDeniedHandler accessDeniedHandler;
@Qualifier("userDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private DataSource dataSource;
@Autowired
private PersistentTokenRepository persistentTokenRepository; @Bean
public PersistentTokenRepository getPersistentTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource); // 数据源注入
jdbcTokenRepository.setCreateTableOnStartup(false); // 由Security完成Token表的创建,如果有了就设置false关闭
return jdbcTokenRepository;
} @Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
} @Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin(). // 设置登陆行为方式为表单登陆
// 登陆请求参数设置
usernameParameter("username").
passwordParameter("password"). loginPage("/login.html"). // 设置登陆页面URL路径
loginProcessingUrl("/login.action"). // 设置表单提交URL路径 successForwardUrl("/main.page"). // 设置认证成功跳转URL路径 POST请求
failureForwardUrl("/error.page"); // 设置认证失败跳转URL路径 POST请求 // successHandler(new FarsAuthenticationSuccessHandler("https://www.acfun.cn/")). // 使用自定义的重定向登陆
// failureHandler(new FarsAuthenticationFailureHandler("/error.html")).; // 跨域处理,不需要跳转了 httpSecurity.authorizeRequests().
regexMatchers(HttpMethod.POST, "正则表达式").permitAll(). // 还可以对符合正则表达式的请求方式进行要求,这个属性使用来制定请求的方式 antMatchers("/**/*.js", "/**/*.css", "/**/images/*.*").permitAll(). // 静态资源放行 antMatchers("/login.html").permitAll(). // 登陆页面允许任意访问
antMatchers("/error.html").permitAll(). // 失败跳转后重定向的页面也需要被允许访问
antMatchers("/admin.page").hasAnyAuthority("admin"). /*antMatchers("/vip-01.page").hasAnyAuthority("vip-01").*/
antMatchers("/vip-01.page").hasRole("vip-01").
antMatchers("/ip.page").hasIpAddress("192.168.43.180"). // mvcMatchers("/main.page").servletPath("/xxx").permitAll(). // mvcMatchers资源放行匹配
// antMatchers("/xxx/main.page").permitAll(). // 或者多写MSP的前缀 anyRequest().authenticated(); // 其他请求均需要被授权访问
// anyRequest().access("@customServiceImpl.hasPermission(request, authentication)"); // 自定义Access配置 // CSRF攻击拦截关闭
httpSecurity.csrf().disable();
httpSecurity.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 记住我
httpSecurity.rememberMe().
tokenValiditySeconds(60). // 设置Token有效时间, 以秒为单位取值
userDetailsService(userDetailsService).
tokenRepository(persistentTokenRepository); // 退出登录处理
httpSecurity.logout().logoutSuccessUrl("/login.html"
);
}
}

如果需要配置独特的退出URL也可以设置:

// 退出登录处理
httpSecurity.
logout().
// logoutUrl("/xxx/xxx/logout").
logoutSuccessUrl("/login.html");

【Spring-Security】Re08 Thymeleaf权限控制 与 退出功能的更多相关文章

  1. Spring Security 动态url权限控制(三)

    一.前言 本篇文章将讲述Spring Security 动态分配url权限,未登录权限控制,登录过后根据登录用户角色授予访问url权限 基本环境 spring-boot 2.1.8 mybatis-p ...

  2. 别再让你的微服务裸奔了,基于 Spring Session & Spring Security 微服务权限控制

    微服务架构 网关:路由用户请求到指定服务,转发前端 Cookie 中包含的 Session 信息: 用户服务:用户登录认证(Authentication),用户授权(Authority),用户管理(R ...

  3. spring security采用自定义登录页和退出功能

    更新... 首先采用的是XML配置方式,请先查看  初识Spring security-添加security 在之前的示例中进行代码修改 项目结构如下: 一.修改spring-security.xml ...

  4. Spring Security实现RBAC权限管理

    Spring Security实现RBAC权限管理 一.简介 在企业应用中,认证和授权是非常重要的一部分内容,业界最出名的两个框架就是大名鼎鼎的 Shiro和Spring Security.由于Spr ...

  5. 登陆模块,这个是很重要的模块,有shiro和spring security专门的权限认证框架

    登陆模块,这个是很重要的模块,有shiro和spring security专门的权限认证框架

  6. spring security实现记住我下次自动登录功能

    目录 spring security实现记住我下次自动登录功能 一.原理分析 二.实现方式 2.1 简单实现方式 2.2 数据库实现方式 三.区分是密码登录还是rememberme登录 spring ...

  7. Atitit.用户权限服务 登录退出功能

    Atitit.用户权限服务 登录退出功能 参数说明 /com.attilax/user/loginOut.jsp?url="+url Utype=mer 作者::  ★(attilax)&g ...

  8. Spring Security 自定义 登陆 权限验证

    转载于:https://www.jianshu.com/p/6b8fb59b614b 项目简介 基于Spring Cloud 的项目,Spring Cloud是在Spring Boot上搭建的所以按照 ...

  9. spring security 登录、权限管理配置

    登录流程 1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)  2)用户发出请求  3)过滤器拦截(MySecurityFil ...

  10. 基于Spring AOP实现的权限控制

    1.AOP简介 AOP,面向切面编程,往往被定义为促使软件系统实现关注点的分离的技术.系统是由许多不同的组件所组成的,每一个组件负责一块特定的功能.除了实现自身核心功能之外,这些组件还经常承担着额外的 ...

随机推荐

  1. react mock数据

    为什么要做假数据,因为后端开发接口没有哪么快,此时就需要自己来模拟请求数据. 模拟的数据字段,需要和后端工程师沟通. 创建所需数据的json文件 json-server 此命令可以帮助我们快速创建一个 ...

  2. Keil一键添加.c文件和头文件路径脚本--可遍历添加整个文件夹

    最近想移植个LVGL玩玩,发现文件实在是太多了,加的手疼都没搞完,实在不想搞了就去找脚本和工具,基本没找到一个...... 主要是自己也懒得去研究写脚本,偶然搜到了一个博主写的脚本,原博客地址:htt ...

  3. SMB3.0多通道叠加双网卡提速

    SMB3.0多通道叠加双网卡提速 (双网卡.多网卡,NAS,局域网共享速度) WIN8及以上是默认开启的.(WIN10.WIN11 默认开启) 只需要同规格的网卡,比如你一张是1Gbps的,另一张网卡 ...

  4. 记一次 .NET某游戏币自助机后端 内存暴涨分析

    一:背景 1. 讲故事 前些天有位朋友找到我,说他们的程序内存会偶发性暴涨,自己分析了下是非托管内存问题,让我帮忙看下怎么回事?哈哈,看到这个dump我还是非常有兴趣的,居然还有这种游戏币自助机类型的 ...

  5. monaco-editor 的 Language Services

    我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品.我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值. 本文作者:修能 这是一段平平无奇的 SQL 语法 SELECT id ...

  6. MYSQL8-快速生成表结构(用于生成文档)

    各种工具都有,没有特别趁手的.不如自己用sql处理. SELECT column_name AS CODE, CASE WHEN column_comment IS NULL OR TRIM(colu ...

  7. Markdown 文章 跳转

    背景 在查阅一些文档的时候,一些比较优秀博客在文章中是带有目录的,点击就会跳转到指定的锚点. 在本人的某些文章中,也想尝试这样的效果. 做法 实现这样的效果有2种做法(不同之处在于 超链接的写法不同) ...

  8. [python] Python日志记录库loguru使用指北

    Loguru是一个功能强大且易于使用的开源Python日志记录库.它建立在Python标准库中的logging模块之上,并提供了更加简洁直观.功能丰富的接口.Logging模块的使用见:Python日 ...

  9. 超快的 Python 包管理工具「GitHub 热点速览」

    天下武功,无坚不破,唯快不破! 要想赢得程序员的欢心,工具的速度至关重要.仅需这一优势,即可使其在众多竞争对手中脱颖而出,迅速赢得开发者的偏爱.以这款号称下一代极速 Python 包管理工具--uv ...

  10. CF1864C 题解

    \(x = 2^k\) 是好做的,每次以 \(2^{k-1}\) 为因数即可. 对于其他情况,考虑每次让 \(x\) 减去其二进制下最低位的 \(1\) 直至变成 \(2^k\). 这种策略下显然每个 ...