Security rules not recognised by Thymeleaf

Asked

Viewed 93 times

1

Hello. Despite defining the rules for spring security and calling in html in an apparently correct way, permissions are not recognized when running the browser. A user without permission ADMINISTRADORcan view a button even without having the rule.

Button that should only be shown to administrators:

        <li sec:authorize="hasRole('ADMINISTRADOR')" class="liindex nav-item">
            <a th:href="@{/usuarios/login}" class="btnpadrao btn btn-sm">Administrador</a>
        </li>

The button appears even if you are logged in with an account without admin permission:

Botão aparecendo

Settings where permission is set.

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception{
        builder.inMemoryAuthentication()
                .withUser("welber").password("123").roles("ADMINISTRADOR")
                .and()
                .withUser("bianca").password("123").roles("COMUM");
    }

COMPLETE SOURCE CODE:

Class complete with rules:

package br.com.welberdev.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

@Configuration
public class InMemorySecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception{
        builder.inMemoryAuthentication()
                .withUser("welber").password("123").roles("ADMINISTRADOR")
                .and()
                .withUser("bianca").password("123").roles("COMUM");
    }
}

HTML where the problem is shown:

<!DOCTYPE html>
<html lang="pt-br"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <title>CatDog</title>
    <link th:href="@{/css/style.css}" rel="stylesheet"/>
    <link th:href="@{/webjars/bootstrap/4.1.0/css/bootstrap.min.css}" rel="stylesheet"/>
</head>

<body class="body-config">
<header>
    <nav class="alteracoes-navbar navbar navbar-expand-lg">
        <div class="container">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a href="" class="nav-link"><img th:src="@{/img/logo_superior1.png}" width="50" height="50"
                                                     alt="CatDog"/></a>
                </li>
                <li class="liindex nav-item">
                    <a th:href="@{/ocorrencias/listar}" class="alink nav-link">Ocorrências</a>
                </li>
                <li class="liindex nav-item">
                    <a href="contato.html" class="alink nav-link">Contato</a>
                </li>
                <li class="liindex nav-item">
                    <a href="outros/localizacao.html" class="alink nav-link">Localização</a>
                </li>
                <li class="liindex nav-item">
                    <a href="sobre.html" class="alink nav-link">Sobre nós</a>
                </li>
                <li class="liindex nav-item">
                    <a th:href="@{/usuarios/login}" class="btnpadrao btn btn-sm">Entrar</a>
                </li>
                <li sec:authorize="hasRole('ADMINISTRADOR')" class="liindex nav-item">
                    <a th:href="@{/usuarios/login}" class="btnpadrao btn btn-sm">Administrador</a>
                </li>
                <li class="lifacebook nav-item">
                    <a target="_blank" href="https://www.facebook.com/groups/275221866151012/"><img
                            class="imgimagemfacebook" th:src="@{/img/facebook.png}"/></a>
                </li>
                <li class="liindex nav-item lisair">
                    <form action="/logout" method="post" class="navbar-form navbar-right">
                        <button type="submit" class="btnpadrao btn btn-sm">Sair</button>
                        <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
                    </form>
                </li>
            </ul>
        </div>
    </nav>
</header>

<main class="main-config">
    <div style="background-color: white" class="centralizado jumbotron fundoprincipal">
        <div th:if="animais != null" class="container">
            <div class="row">
                <div th:each="animal : ${listaDeAnimais}" class="col-sm-6 col-md-4">
                    <div class="card-config card">
                        <img src="../img/gatopainel.png" class="card-img-top" alt="Foto do animal"/>
                        <div class="card-body">
                            <h5 class="card-title" th:text="${animal.nomeAnimal}"></h5>
                            <p class="card-text" th:text="${animal.historiaAnimal}"></p>
                            <p class="card-text">
                                <small class="text-muted">Postado em</small>
                                <small th:text="${animal.dataEncontroAnimal}"></small>
                                <small th:text="${animal.idAnimal}" hidden="hidden"></small>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script th:src="@{/js/jquery-3.3.1.min.js}"></script>
<script th:src="@{https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js}" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
</html>

Configuration of permissions:

package br.com.welberdev.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/animais/admin/*", "/usuarios/admin/*").hasAnyRole("ADMINISTRADOR")
                    .antMatchers("/ocorrencias/comum/*").hasAnyRole("COMUM")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                    .loginPage("/usuarios/login")
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessUrl("/usuarios/login?logout")
                    .permitAll();
    }
}

POM.XML:

<?xml version="1.0" encoding="UTF-8"?>
<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>br.com.welberdev</groupId>
    <artifactId>ajudaf</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--Aqui foi declarada a versão do spring e, portanto, as dependencias não precisam-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
    <!--Fim-->

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--Dependências padrão para o Spring. (O starter garante um pacote com tudo que precisamos, sem aquele monte de importações)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
        <!--Fim-->

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--Plugin para comunicação do spring com o maven-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!--Fim-->
        </plugins>
    </build>
</project>

1 answer

1


I solved the problem by replacing the following method:

@Bean
    public SpringTemplateEngine templateEngine (SpringResourceTemplateResolver resolver){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(resolver);
        return templateEngine;
    }

By the method:

@Bean
public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.addDialect(new SpringSecurityDialect());
    return templateEngine;
}

I am still trying to understand what actually happened, but I assume I had not defined the dialect in my templateResolver. I might be wrong, because I’m new to these tools. So if someone has a collaboration, it would be of paramount importance to understanding the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.