Using Spring Boot 1.5.2 and Thymeleaf 2.1, I'm trying to add some code on an HTML page to identify the role of a user.
However, all of these statements evaluate to true which is incorrect:
<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>
User.java
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
Role.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;
}
}
I fixed the issue. I was missing three items:
thymeleaf-extras-springsecurity4
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
xmlns:sec in the html template
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
Correct output
"Has authority USER" is now displayed when the template is rendered when a user with ROLE=USER is logged in
<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div>
Check definition xmlns:sec in part of your template - html.
Do you have sec defined in your html section of the page. Like this:
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">