4

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~

6
  • .But now it always display on the page is it the login page?
    – Sal-laS
    Commented Dec 21, 2017 at 8:34
  • this element was written on index.html.And i can see both of messages.But the user don't have any roles.
    – StupidPz
    Commented Dec 21, 2017 at 8:47
  • I cannot find configAuthentication(AuthenticationManagerBuilder auth) method. is a jdbcAuthentication an acceptable solution for you?
    – Sal-laS
    Commented Dec 21, 2017 at 9:21
  • @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); auth.authenticationProvider(daoAuthenticationProvider()); } is this what u were looking for?
    – StupidPz
    Commented Dec 21, 2017 at 9:47
  • maybe but i guess it should be called configAuthentication. But, unfortunatlly, i haven't work with userDetailsService. instead i can help you with jdbcAuthentication. would it be helpfull?
    – Sal-laS
    Commented Dec 21, 2017 at 9:55

2 Answers 2

8

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.

0

WHat you are missing here is a tag in your HTML

xmlns:sec="http://www.thymeleaf.org/extras/spring-security".

You don't really need xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" tag anyways if you're using Springboot.

Not the answer you're looking for? Browse other questions tagged or ask your own question.