簡體   English   中英

Thymeleaf中的Spring安全性表達式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM