使用 Spring Boot 1.5.2 和 Thymeleaf 2.1,我试图在 HTML 页面上添加一些代码来识别用户的角色。
但是,所有这些陈述的计算结果都是正确的,这是不正确的:
<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>
用户.java
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
角色.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;
}
}
最佳答案
我解决了这个问题。我遗漏了三个项目:
thymeleaf-extras-springsecurity4
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
html模板中的xmlns:sec
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
正确输出
当具有 ROLE=USER 的用户登录时呈现模板时,现在会显示“具有权限 USER”
<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div>
关于java - Thymeleaf 中的 Spring 安全表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906027/