当前位置: 首页 > 知识库问答 >
问题:

Spring Boot Security-Thymeleaf sec:授权不工作

赫连方伟
2023-03-14

我正在尝试使用Spring Boot、Spring Security4、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>

这是我的securityconfig

    @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个答案

钱哲茂
2023-03-14

我使用的是springboot1.5.8.releasethymeleaf3.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里。

 类似资料:
  • 我有以下Spring Security配置: 我想让每个人(包括经过身份验证的用户和未经身份验证的用户)都可以访问特定的页面(比如索引页面(“/”),但同时,能够根据用户是否经过身份验证以及其角色来管理应该在jsp中看到哪些部分。 我的jsp部分如下所示: 所有的认证机制都可以正常工作。问题是,即使我使用“管理员”角色登录,链接也永远不会显示。 我尝试调试我的userdetails服务实现,并验证

  • 我发现了许多类似的问题,但没有一个解决了我的问题。我的问题是可以访问的函数 下面是我的spring-security.xml代码。

  • 默认情况下,SEC:authorize-URL标记不适用于Spring boot security: 添加依赖项 我是不是漏掉了什么?这是预期的行为吗?我需要定义什么才能使authorize-url像使用XML配置安全性时那样工作? 此问题与SpringBootWebSecurityConfiguration中的基本身份验证及其自动配置有关: 在SampleMethodSecurityApplic

  • 我正在尝试使用aws api网关授权器和cognito用户池。当我使用aws api网关控制台进行测试时,它工作得很好。 但当我尝试在api中启用授权时,它显示请查看下面的屏幕截图 有人能帮忙吗。

  • 我正在使用 Artifactory 2.4.0 和 Jenkins 1.438,我有一个包含多个模块的 maven 项目。需要将所有模块(jars和一场由此产生的战争)部署到Jenkins的远程Artifactory服务器中。 我的artifactory用户管理员使用默认密码(password),我尝试在jenkins上执行的所有构建都可以正常工作。因此,当我决定更改de Artifactory管

  • 我正在学习一个关于微软文档的教程,介绍如何使用Spring Boot Starter for Azure Active Directory保护我的Spring MVC应用程序。我正在努力保护我网站的管理区域。我在控制器方法上有一个@PreAuthorize注释,我只希望admin组中的用户可以访问它。我可以得到一个登录提示,但成功登录后,我得到了该控制器方法的403。当我删除@PreAuthori