How to hide menu items using spring security?

Asked

Viewed 771 times

5

I am using spring security to control access to my web application. I have already managed to implement the control that each type of user will have in relation to the urls, now I would like to hide the items for the common user that will be restricted to admin users only. I have implemented it in many ways and I have not succeeded. Someone can help me?

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());
}

}

In case I want to hide the items: Suppliers and Logs so that only users with the tags ROLE_ADMIN can see.

  • @Brunocésar in the bank this ROLE_ADMIN, I’ve seen videos that in webconfig do not need to put the ROLE, because it is already implicit by spring. role should not start with 'ROLE_' Since it is Automatically inserted. Got 'ROLE_ADMIN', So it’s only ADMIN, ai in html already tested with ROLE_ and so ADMIN, but none works

  • 1

    I don’t remember having this attribute access in this module of Thymeleaf. Besides this you are using wrong, use in a div or in the list item add the sec:authorize="hasRole('ROLE_ADMIN')", getting <li sec:authorize="hasRole('ROLE_ADMIN')"><a th:href="@{/fornecedor/lista}"><i class="fa fa-drivers-license-o"></i>Fornecedores</a></li>. I can’t test now, anything coming home I take a test.

  • @Brunsyou can try here, could you help me on this other issue? https://answall.com/questions/304574/duvida-no-relateddata-de-data-co-data%C3%A7%C3%A3o-using-spring-boot

  • @Brunocésar put as mentioned, but still displaying normally, strange, it seems that the problem is no longer in html.

2 answers

1


Friend, add to your menu item a th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}", so this item will only be shown if the user has this permission.

0

Good morning

You can use th:if or th:unless from Thymeleaf to render or not a part of 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>

Browser other questions tagged

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