2017-03-20 65 views
0

使用Spring Boot 1.5.2和Thymeleaf 2.1,我试图在HTML页面上添加一些代码来标识用户的角色。Thymeleaf中的Spring Security表达式

然而,所有这些语句的评价为真哪个是不正确的:

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

} 

回答

4

我修复了这个问题。我错过了三个项目:

thymeleaf-额外-springsecurity4

<dependency> 
    <groupId>org.thymeleaf.extras</groupId> 
    <artifactId>thymeleaf-extras-springsecurity4</artifactId> 
</dependency> 

的xmlns:秒在HTML模板

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" 
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> 

正确的输出

“有权威用户“现在显示n在ROLE = USER的用户登录时呈现模板

<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div> 
-1

听起来很奇..

您确定已将Thymeleaf添加到您的项目中吗?

如果Thymeleaf没有包含在您的项目/文件中,那么html页面将呈现为常规html页面。因此,它可能看起来像你有所有角色,但实际上,该网站只是呈现为普通的HTML。

您可以检查您的Thymeleaf正确地与此渲染:

<p th:text="Hello World!" /> 
0

入住模板的一部分定义xmlns:sec - html

0

是否在页面的html部分中定义了sec?像这样:

<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> 
相关问题