springboot中使用thymeleaf-extras-springsecurity实现权限管理

熵烬
• 阅读 7223

环境

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

导入依赖

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


<!--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,如下

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官方地址


一些常用的属性:

// 展示登录名
<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>

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

登录注销小案例

<!--登录注销-->
            <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"

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Easter79 Easter79
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
熵烬
熵烬
Lv1
江汉思归客,乾坤一腐儒
文章
3
粉丝
0
获赞
0