Spring Boot 安全性 - Thymeleaf sec:授权不起作用 [英] Spring Boot Security - Thymeleaf sec:authorize not working

查看:57
本文介绍了Spring Boot 安全性 - Thymeleaf sec:授权不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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">客人</p>

<div sec:authorize="hasRole('ROLE_ADMIN')"><p class="bg-info">如果您有权限访问role_admin</p>就可以看到这个

这是我的 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><父母><groupId>com.zhongdihang.resp</groupId><artifactId>resp-parent</artifactId><version>1.0.0</version><relativePath>../resp-parent</relativePath></父母><artifactId>resp-serve</artifactId><包装>战争</包装><name>房产共享平台服务</name><description>房产共享平台服务</description><依赖项><!-- 编译--><依赖><groupId>com.zhongdihang.resp</groupId><artifactId>resp</artifactId></依赖><依赖><groupId>com.zhongdihang.resp</groupId><artifactId>resp-test</artifactId></依赖><依赖><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></依赖><依赖><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></依赖><依赖><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></依赖><依赖><groupId>org.springframework.session</groupId><artifactId>spring-session-jdbc</artifactId></依赖><!-- 可选--><依赖><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></依赖><!-- 运行时--><依赖><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>运行时</scope></依赖><依赖><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><scope>运行时</scope><version>11.2.0.4</version></依赖><依赖><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.12</version></依赖><依赖><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></依赖><依赖><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version><scope>运行时</scope></依赖><依赖><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></依赖><依赖><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></依赖><!--mapper --><依赖><groupId>net.sf.dozer</groupId><artifactId>推土机</artifactId><version>5.4.0</version><排除事项><排除><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId></排除><排除><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId></排除><排除><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></排除></排除项></依赖><!--<依赖><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></依赖>--><依赖><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId></依赖></依赖项><构建><插件><插件><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><执行><执行><目标><目标>重新打包</目标></目标></执行></执行></插件></plugins></build></项目>

这是我的安全配置

 @Configuration@启用网络安全@EnableGlobalMethodSecurity(prePostEnabled = true)公共类 SecurityConfig 扩展了 WebSecurityConfigurerAdapter {@自动连线私人密码编码器密码编码器;@自动连线私有角色服务角色服务;@自动连线private SecurityUserDetailsS​​ervice userDetailsS​​ervice;@豆公共 DaoAuthenticationProvider daoAuthenticationProvider() {DaoAuthenticationProvider provider = new DaoAuthenticationProvider();provider.setUserDetailsS​​ervice(userDetailsS​​ervice);provider.setPasswordEncoder(passwordEncoder);返回提供者;}@Value("${" + ApplicationConstants.THIS_APP_CONFIG_PREFIX + ".security.debug:false}")私有布尔调试 = 假;@自动连线public void configureGlobalSecurity(AuthenticationManagerBuilder auth) 抛出异常 {auth.userDetailsS​​ervice(userDetailsS​​ervice);auth.authenticationProvider(daoAuthenticationProvider());}private void configureExceptionHandling(ExceptionHandlingConfigurer<HttpSecurity> handler) {handler.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());}private void configureAuthorizeRequests(ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry) {//registry.accessDecisionManager(new SecurityAccessDecisionManager());registry.antMatchers("/login/**","/auth/**","/api/open/person/**","/api/booking/**","/api/module/menu","/api/booking").permitAll();列表<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) 抛出异常 {//http.addFilterBefore(new SecurityAuthorizationFilter(sessionrepo),//UsernamePasswordAuthenticationFilter.class);}@覆盖protected void configure(HttpSecurity http) 抛出异常 {http.headers().frameOptions().disable();配置过滤器(http);configureExceptionHandling(http.exceptionHandling());configureAuthorizeRequests(http.authorizeRequests());http.csrf().disable();http.formLogin().loginPage("/登录").usernameParameter("用户名").passwordParameter("密码").failureHandler(new SecurityAauthenticationFailureHandler()).successHandler(new SecurityAuthenticationSuccessHandler()).permitAll();http.logout().logoutUrl("/注销").logoutSuccessHandler(new SecurityLogoutSuccessHandler()).permitAll();}@覆盖公共无效配置(WebSecurity web)抛出异常{网络调试(调试);web.ignoring().antMatchers(HttpMethod.OPTIONS);web.ignoring().antMatchers("/assets/**");web.ignoring().antMatchers("/**.ico");web.ignoring().antMatchers("/v2/api-docs");}}

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

解决方案

我用的是 springboot 1.5.8.RELEASE thymeleaf 3.0.9.RELEASE,所以我需要使用最新的 org.thymeleaf.extras.so 尝试添加

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

在你的 pom 中.

I'm trying to use Spring Boot, Spring Security 4, Thymeleaf.And if the user has role"admin" or anything else.The html block should be shown up.But now it always display on the page. Here is my 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>

And here is my pom.xml i do add the thymeleaf-extras-springsecurity4. Also tried 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>

And here is my 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");
    }
}

Anybody can help me? thank you so much~

解决方案

I'm using springboot 1.5.8.RELEASE thymeleaf 3.0.9.RELEASE,so i need to use latest org.thymeleaf.extras.so try to add

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

in you pom.

这篇关于Spring Boot 安全性 - Thymeleaf sec:授权不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆