Spring Boot 安全 - Thymeleaf sec:授权不起作用

2024-04-22

我正在尝试使用 Spring Boot、Spring Security 4、Thymeleaf。如果用户具有“admin”角色或其他角色。应该显示 html 块。但现在它始终显示在页面上。 这是我的html

<html lang="en" xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<div sec:authorize="hasRole('ROLE_GUEST')">
    <p class="bg-info">guest</p>
    </div>
    <div sec:authorize="hasRole('ROLE_ADMIN')">
        <p class="bg-info">you can see this if you have permission to acess role_admin</p>
    </div>

这是我的 pom.xml,我添加了 thymeleaf-extras-springsecurity4。还尝试了 thymeleaf-extras-springsecurity3

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zhongdihang.resp</groupId>
        <artifactId>resp-parent</artifactId>
        <version>1.0.0</version>
        <relativePath>../resp-parent</relativePath>
    </parent>
    <artifactId>resp-serve</artifactId>
    <packaging>war</packaging>
    <name>Real estate sharing platform serve</name>
    <description>Real estate sharing platform serve</description>
    <dependencies>
        <!-- Compile -->
        <dependency>
            <groupId>com.zhongdihang.resp</groupId>
            <artifactId>resp</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zhongdihang.resp</groupId>
            <artifactId>resp-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <!-- Optional -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Runtime -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <scope>runtime</scope>
            <version>11.2.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--mapper -->
        <dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.4.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--  
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

这是我的安全配置

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleService roleService;


    @Autowired
    private SecurityUserDetailsService userDetailsService;

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        return provider;
    }

    @Value("${" + ApplicationConstants.THIS_APP_CONFIG_PREFIX + ".security.debug:false}")
    private boolean debug = false;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    private void configureExceptionHandling(ExceptionHandlingConfigurer<HttpSecurity> handler) {
        handler.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());
    }
    private void configureAuthorizeRequests(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) {
        //registry.accessDecisionManager(new SecurityAccessDecisionManager());      
        registry.antMatchers("/login/**","/auth/**","/api/open/person/**","/api/booking/**","/api/module/menu","/api/booking").permitAll();
        List<RoleEntity> list = roleService.findAll();
        for (RoleEntity roleEntity : list) {
            if(roleEntity.getModule()!=null) {
                registry.antMatchers(roleEntity.getModule().getPath()+"/**").hasAuthority(roleEntity.getNumber()).anyRequest().authenticated();
            }
        }
        registry.anyRequest().authenticated();
        //registry.anyRequest().hasAnyRole("ADMINISTRATOR");
    }

    private void configureFilter(HttpSecurity http) throws Exception {
         //http.addFilterBefore(new SecurityAuthorizationFilter(sessionrepo),
         //UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        configureFilter(http);
        configureExceptionHandling(http.exceptionHandling());
        configureAuthorizeRequests(http.authorizeRequests());
        http.csrf().disable();
        http.formLogin()
            .loginPage("/login")
            .usernameParameter("username")
            .passwordParameter("password")
            .failureHandler(new SecurityAauthenticationFailureHandler())
            .successHandler(new SecurityAuthenticationSuccessHandler())
            .permitAll();
        http.logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new SecurityLogoutSuccessHandler())
            .permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(debug);
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
        web.ignoring().antMatchers("/assets/**");
        web.ignoring().antMatchers("/**.ico");
        web.ignoring().antMatchers("/v2/api-docs");
    }
}

有人可以帮助我吗? 非常感谢你~


我正在使用弹簧靴1.5.8.RELEASE百里香叶3.0.9.RELEASE,所以我需要使用最新的org.thymeleaf.extras.所以尝试添加

       <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>

在你的pom中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot 安全 - Thymeleaf sec:授权不起作用 的相关文章

随机推荐

  • 如何完全清除所有 matplotlib 图的内存

    我有一个数据分析模块 其中包含调用的函数matplotlib pyplotAPI 多次 每次运行最多生成 30 个数字 这些数字在生成后会立即写入磁盘 因此我需要将它们从内存中清除 目前 在每个函数结束时 我都会 import matplo
  • 如何使用 drf-yasg 自动生成的 swagger 页面配置“HTTPS”方案?

    我知道在传统的 swagger YAML 文件中 我们可以使用以下方式定义方案 schemes http https OR schemes http https 但是 我如何使用自动生成的 swagger 页面做同样的事情drf yasg图
  • Android MediaRecorder 和 setOutputFile

    我阅读了 Android SDK 发现 MediaRecorder 类可以从相机 音频或其他源获取输入并对其进行压缩 通过 setOutputFile 方法 您可以指定要存储数据的位置 文件或 URI 但是如果我想将该数据存储在内存缓冲区中
  • 将字符向量列表转换为数据帧

    我的输出 a 看起来像 str a List of 8883695 chr 1 3 20MICRONS A ACCRUALS chr 1 3 20MICRONS A ACCRUALS chr 1 3 20MICRONS A ACCRUALS
  • 检查针对 SQL Server 数据库的 LINQ 查询

    有什么方法可以在 NET 中查看我们正在触发的针对数据库的 LINQ 查询吗 例如 我正在 LINQ 中编写一个查询 我想看看触发了什么 SQL 查询来与数据库进行通信 有没有 Visual Studio 窗口或其他方式 你在寻找类似的东西
  • 带 python 列表的循环引用

    有人可以解释一下吗 gt gt gt x x 0 0 gt gt gt x gt gt gt x is x 0 True gt gt gt x 0 0 0 0 0 0 0 gt gt gt x in x True what is 这只是 P
  • OpenCV 3.0.0 使用 FFMPEG 时出错

    我使用 OpenCV 一段时间了 但是 我最近将系统更改为没有任何管理员权限的集群 问题是这样的 在我的主文件夹中 我安装了 FFMPEG ffmpeg 网站上提供的最新稳定版本 我将它安装在 HOME 中 因此在 HOME lib 中安装
  • sso 用户的 s3 存储桶策略

    我想允许特定角色 test role 在特定存储桶 test bucket 上执行所有 s3 操作 拒绝为所有其他人提供桶 我写的 s3 策略 Version 2012 10 17 Id Policy1601973417173 Statem
  • 以编程方式发送自动电子邮件[重复]

    这个问题在这里已经有答案了 我想以编程方式发送电子邮件 我尝试了以下代码 最终意图 emailIntent 新意图 android content Intent ACTION SEND emailIntent setType plain t
  • iOS:Firebase 令牌返回 null

    我目前正在尝试按照 Firebase 官方文档来实现 Firebase Cloud Messaging 我已在启用推送通知的情况下解决了证书和配置文件的问题 我还使用 CocoaPods 安装了所有必要的框架 FirebaseMessagi
  • 将 LinkBut​​ton 的 OnClick 事件设置为代码隐藏中的方法

    我正在从我的代码隐藏构造一个 LinkBut ton 我需要将 onclick 分配给一个方法 并用它传递一个参数 到目前为止我有这个 LinkButton lnkdel new LinkButton lnkdel Text Delete
  • 在 FIFO 上写入“复杂”结构

    我正在使用 C 语言与客户端服务器进行某种 餐厅 实现 我正在尝试通过 FIFO 发送以下结构 typedef struct int numtable table number to send answer char timestamp 2
  • 没有带有常量“模板参数”的 F# 泛型?

    我突然想到 F 泛型似乎不接受常量值作为 模板参数 假设有人想创建一种类型RangedInt这样 它的行为类似于 int 但保证只包含整数值的子范围 一种可能的方法是建立受歧视的工会 类似于 type RangedInt Valid of
  • 使用 ggplot 约束 stat_smooth 中的斜率(绘制 ANCOVA)

    Using ggplot 我试图绘制 ANCOVA 的结果 其中两个线性分量的斜率相等 即lm y x A 默认行为为geom smooth method lm 是为每个因子的每个水平绘制单独的斜率和截距 例如 有两个级别A library
  • 具有两个以上固定效应的 Python 面板数据回归

    我有一个面板数据库 想运行考虑固定效应的回归 使用Panel Ols 时 两个固定效果可以正常工作 我的代码如下所示 df countyCode pd Categorical df countyCode df state pd Catego
  • 如何从带有通配符的字符串中获取Appx全名?

    在 Powershell 中 此命令Get AppxPackage name 可以显示包裹的完整详细信息 是否可以使用任何 Windows API 来获得等效结果 我见过这个question https stackoverflow com
  • python cdist 错误 ValueError: XA 必须是二维数组

    这是我的代码的缩短版本 dist array ssd cdist test y training test y 打印的是 0 00000000e 00 1 79900000e 01 1 03800000e 01 1 22800000e 02
  • 在 SQL 中获取运行总计最大值的高性能方法

    我们有一个交易表 其结构如下 TranxID int PK and Identity field ItemID int TranxDate datetime TranxAmt money TranxAmt 可以是正数或负数 因此该字段 对于
  • PostgreSQL 对连接中的表数量有限制吗?

    今天在玩动态查询生成时 我发现 mysql 对连接中可以使用的表数量有一个硬性最大限制 61 这让我想知道 PostgreSQL 是否有类似的限制 注 我问这个是出于好奇 而不是需要 据我所知没有限制 一旦超过 可配置的 表限制 查询优化器
  • Spring Boot 安全 - Thymeleaf sec:授权不起作用

    我正在尝试使用 Spring Boot Spring Security 4 Thymeleaf 如果用户具有 admin 角色或其他角色 应该显示 html 块 但现在它始终显示在页面上 这是我的html div p class bg in