5

Estou utilizando o spring security para controle de acesso a minha aplicaçao web. Ja consegui implementar o controle que cada tipo de usuario terá em relaçao as urls, agora gostaria de ocultar os itens para o usuario comum que ficarão restritos a somente usuarios admin. Ja implementei de varias maneiras e nenhum obtive exito. Alguem pode me ajudar?

POM.XML:

<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>

Index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>CompraFacil</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="all,follow">
<!-- Bootstrap CSS-->
<link rel="stylesheet" href="/css/bootstrap.min.css">

<!-- Google fonts - Roboto -->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Poppins:300,400,700">
<!-- theme stylesheet-->
<link rel="stylesheet" href="/css/style.blue.css" id="theme-stylesheet">
<!-- Custom stylesheet - for your changes-->
<link rel="stylesheet" href="/css/custom.css">
<!-- Favicon-->
<link rel="shortcut icon" href="img/favicon.ico">
<!-- you can replace it by local Font Awesome-->
<script src="https://use.fontawesome.com/99347ac47f.js"></script>
<!-- Font Icons CSS-->
<link rel="stylesheet"
href="https://file.myfontastic.com/da58YPMQ7U5HY8Rb6UxkNf/icons.css">
<link
href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"
rel="stylesheet" type="text/css">
<script src="/javascripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="page home-page" th:fragment="header">
    <!-- Main Navbar-->
    <header class="header">
        <nav class="navbar">
            <div class="container-fluid">
                <div
                    class="navbar-holder d-flex align-items-center justify-content-between">
                    <!-- Navbar Header-->
                    <div class="navbar-header">
                        <!-- Navbar Brand -->
                        <div class="brand-text brand-big hidden-lg-down">
                            <span>Compra Facil </span>
                        </div>
                    </div>
                    <!-- Logout    -->
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i
                        class="fa fa-user"></i> Conta <b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li><a href="@{Funcionarios.perfil}"><i
                                class="fa fa-fw fa-user"></i> Perfil</a></li>
                        <li><a href="@{Funcionarios.formTrocarSenha}"><i
                                class="fa fa-fw fa-gear"></i> Alterar senha</a></li>
                        <li class="divider"></li>
                        <li><a href="/login?logout"><i
                                class="fa fa-fw fa-power-off"></i> Log Out</a></li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="page-content d-flex align-items-stretch">
        <!-- Side Navbar -->
        <nav class="side-navbar">
            <!-- Sidebar Header-->
            <div class="sidebar-header d-flex align-items-center">
                <div class="avatar">
                    <img src="/img/user_deffault.png" class="img-fluid rounded-circle">
                </div>
                <div class="title">
                    <h1 class="h4">${usuario.nome}</h1>
                    <p><span sec:authentication="usuario.cnpjCpf"></span></p>
                </div>
            </div>
            <!-- Sidebar Navidation Menus-->
            <span class="heading">Principal</span>
            <ul class="list-unstyled">

                <li><a href="/"><i class="fa fa-home"></i>Home</a></li>
                <sec:authorize access="hasRole('ADMIN')">
                <li ><a
                    th:href="@{/fornecedor/lista}"><i
                        class="fa fa-drivers-license-o"></i>Fornecedores</a></li></sec:authorize>
                <li><a href="@{PontosEstrategicos.pontos}"> <i
                        class="fa fa-cubes"></i>Produtos
                </a></li>
                <li><a href="@{Palhetas.listarPalhetas}"><i
                        class="fa fa-clock-o"></i>Agendamentos</a></li>
                <li><a href="@{Denuncias.listarDenuncias}"> <i
                        class="fa fa-cart-plus"></i>Compras
                </a></li>

                <li><a href="@{Relatorios.relatorios}"> <i
                        class="icon-interface-windows"></i>Relatórios
                </a></li>
            </ul>
            <span class="heading">Extra</span>
            <ul class="list-unstyled">
                <li><a href="Doc/Relatorio.pdf"> <i
                        class="fa fa-file-pdf-o"></i>Documentação
                </a></li>
                <li><a data-toggle="modal" data-target="#modalSobre"> <i
                        class="fa fa-info"></i>Sobre
                </a></li>
            </ul>
            <span class="heading">Admin</span>
            <ul class="list-unstyled">
                <li><a href="@{Auditorias.auditoriaLogs}"><i
                        class="fa fa-fw fa fa-history"></i> Logs</a></li>
            </ul>
        </nav>
        <div class="content-inner">
            <!-- Dashboard Counts Section-->
            <div class="row">
                <div class="col-lg-12">
                    <ol class="breadcrumb">
                        <section layout:fragment="corpo">Hello</section>
                    </ol>
                </div>
            </div>
            <!-- Page Footer-->

        </div>
    </div>
</div>

<footer class="main-footer">

    <div class="row">
        <div class="col-sm-6">
            <p>Tecnologia da net &copy; 2018-2019</p>
        </div>
        <div class="col-sm-6 text-right">
            <p>
                Design by <a href="https://bootstrapious.com/admin-templates"
                    class="external">Bootstrapious</a>
            </p>
        </div>
    </div>
</footer>

<!-- The Modal -->
<div id="modalSobre" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Sobre</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                <img src="/img/modal.png" alt="Smiley face" height="300"
                    width="750">
                <h5>
                    <center>Compra Facil plataforma de e-commerce B2C -
                        Versão 1.0</center>
                </h5>
                <h5>
                    <center>Desenvolvido por: Tecnologiadanet</center>
                </h5>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary"
                    data-dismiss="modal">Fechar</button>
            </div>

        </div>
    </div>
</div>

<!-- FIM MODAL -->


<!-- Javascript files-->
<script type="text/javascript" charset="utf8"
    src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8"
    src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script src="/js/tether.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/jquery.cookie.js"></script>
<script src="/js/jquery.validate.min.js"></script>
<script src="/js/front.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/bootstrap-confirmation.js"></script>
<script src="/js/bootstrap-confirmation.min.js"></script>
<script src="/js/jquery.validate.min.js"></script>
<script src="/js/front.js"></script>
<script src="/js/jquery.cookie.js"></script>
<script src="/js/tether.min.js"></script>
<script src="/js/bootstrap-confirmation.js"></script>
<script src="/js/bootstrap-confirmation.min.js"></script>
<script src="/js/modal-remove.js"></script>
<script src="/js/bootbox.min.js"></script>

<!-- script para verificação antes de excluir registro -->
<script>
    $('[data-toggle="confirmation"]').confirmation();
    $(document).ready(function() {
        $(".dropdown-toggle").dropdown();
    });
</script>

WebSecurity:

package com.bigboss.comprafacil.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {

@Autowired
private ImplementsUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/resources/**").permitAll()
        .antMatchers(HttpMethod.GET, "/cadastrarFornecedor").hasRole("ADMIN")
        .antMatchers(HttpMethod.POST, "/cadastrarFornecedor").hasRole("ADMIN")
        .antMatchers(HttpMethod.POST, "/lista").hasRole("ADMIN")
        .and()
        .formLogin()
            .loginPage("/login").permitAll()
        .and()
        .rememberMe()
        .and()
        .logout()
        .logoutSuccessUrl("/login?logout")
        .permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
    auth.userDetailsService(userDetailsService)
    .passwordEncoder(new BCryptPasswordEncoder());
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**").antMatchers("/h2/**");
}
}

ImplementsUserDetails

@Repository
@Transactional
public class ImplementsUserDetailsService implements UserDetailsService{

@Autowired
private UsuarioRepository ur;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Usuario usuario = ur.findByEmail(email);

    if(usuario == null){
        throw new UsernameNotFoundException("Usuario não encontrado!");
    }
    return new User(usuario.getUsername(), usuario.getPassword(), true, true, true, true, usuario.getAuthorities());
}

}

No caso quero ocultar os itens: Fornecedores e Logs para que somente usuarios com as tags ROLE_ADMIN possam ver.

4
  • @BrunoCésar no banco esta ROLE_ADMIN, ja vi videos que no webconfig nao precisa colocar o ROLE, pois ja é implicito pelo spring. role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_ADMIN', Portanto, é somente ADMIN, ai no html ja testei com ROLE_ e so ADMIN, mas nenhum funciona Commented 5/06/2018 às 15:01
  • 1
    Não lembro de ter este atributo access neste module do Thymeleaf. Além disto você está usando errado, use em uma div ou no item da lista adicione o sec:authorize="hasRole('ROLE_ADMIN')", ficando <li sec:authorize="hasRole('ROLE_ADMIN')"><a th:href="@{/fornecedor/lista}"><i class="fa fa-drivers-license-o"></i>Fornecedores</a></li>. Não consigo testar agora, qualquer coisa chegando em casa faço um teste. Commented 5/06/2018 às 15:22
  • @BrunoCésar tentar aqui, voce poderia me ajudar nesta outra questao? pt.stackoverflow.com/questions/304574/… Commented 5/06/2018 às 15:27
  • @BrunoCésar coloquei como mencionou, mas continua exibindo normalmente, estranho, parece que o problema ja nao é no html. Commented 5/06/2018 às 15:29

2 Respostas 2

1

Amigo, adicione no seu item do menu um th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}", assim esse item só será mostrado caso o usuário tenha essa permissão.

0

Bom dia

Você pode utilizar o th:if ou th:unless do thymeleaf para renderizar ou não uma parte do HTML.

<div class="checkbox aw-checkbox-no-margin" th:if="${#authentication.principal.usuario.codigo != usuario.codigo}">
    <input type="checkbox" class="js-selecao" data:codigo="${usuario.codigo}">
    <label></label>
</div>

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .