Usando Spring Boot 1.5.2 y Thymeleaf 2.1, intento agregar un código en una página HTML para identificar el rol de un usuario.
Sin embargo, todas estas declaraciones se evalúan como verdaderas, lo cual es incorrecto:
<div sec:authorize="hasAuthority('ADMIN')" > Has Authority ADMIN </div> <div sec:authorize="hasAuthority('USER')" > Has Authority USER </div> <div sec:authorize="hasRole('ROLE_ADMIN')">Has Role ROLE_ADMIN</div> <div sec:authorize="hasRole('ROLE_USER')">Has Role ROLE_USER</div> <div sec:authorize="hasRole('ADMIN')">Has Role ADMIN</div> <div sec:authorize="hasRole('USER')">Has Role USER</div>Usuario.java
@ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles;Rol.java
@Entity @Table(name = "role") public class Role { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "role") private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }Solucioné el problema. Me faltaban tres elementos:
thymeleaf-extras-springsecurity4
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency>xmlns:sec en la plantilla html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">Salida correcta
Ahora se muestra "Tiene autorización de USUARIO" cuando la plantilla se procesa cuando un usuario con ROLE=USUARIO está conectado
<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div>Verifique la definición xmlns:sec en parte de su plantilla - html .
¿Tiene sec definido en su sección html de la página? Como esto:
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">