[英]Use Spring Security in Thymeleaf escaped expressions in JavaScript
[英]Spring Security Expressions in Thymeleaf
我正在尝试使用Spring Boot 1.5.2和Thymeleaf 2.1在HTML页面上添加一些代码来识别用户的角色。
但是,所有这些语句评估为true,这是不正确的:
<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;
角色.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;
}
}
我解决了这个问题。 我缺少三个项目:
百里香属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的用户登录时呈现模板时,现在显示“具有用户权限”
<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div>
听起来很奇怪。
确定要在项目中包含Thymeleaf?
如果Thymeleaf没有插入您的项目/文件中,则html页面将呈现为常规html页面。 因此,看起来您已经担当了所有角色,但实际上,该网站只是呈现为常规html。
您可以使用以下方法检查Thymeleaf是否正确渲染:
<p th:text="Hello World!" />
在模板html
一部分中检查xmlns:sec
定义。
您是否在页面的html部分中定义了sec。 像这样:
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
您需要导入porm
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
这是为您提供的网站gui https://www.thymeleaf.org/doc/articles/springsecurity.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.