2017-01-02 101 views
2

這是可能的Thymeleaf 3.0:使用Spring Security在Thymeleaf逃脫表達式在JavaScript

/*[# th:if="${user.admin}"]*/ 
    alert('Welcome admin'); 
/*[/]*/ 

但是這不起作用:

/*[# sec:authorize="hasAnyRole('ROLE_ADMIN)"]*/ 
    alert('Welcome admin'); 
/*[/]*/ 

那真的是不可能的還是我做錯了什麼?

我使用Spring Security 4.1。

約逃脫表達分析的一些背景資料:https://github.com/thymeleaf/thymeleaf/issues/395

編輯1

丹尼爾·費爾南德斯發現,在我最初的問題缺少的單引號。

添加它後不幸,它仍然無法正常工作。

表達式被解析,因爲它從生成的html/javascript中消失。

但document.writeln()被執行,即使我沒有登錄,甚至當我在我登錄,我改變檢查sec:authorize="hasRole('ROLE_ADMIN123')

<script type="text/javascript" th:inline="javascript"> 

    /*[# sec:authorize="hasRole('ROLE_ADMIN')"]*/ 
     document.writeln("ADMIN !!!"); 
    /*[/]*/ 

</script> 

編輯2

這是我的解決方法until further notice

創建一個@Service一個方法,並檢查用戶是否具有所需要的角色(S)或不:

import javax.servlet.http.HttpServletRequest; 
import org.springframework.stereotype.Service; 

@Service 
public class UtilService { 

    public boolean hasAnyRole(HttpServletRequest req, String... roles) { 
     for (final String role : roles) { 
      if (req.isUserInRole(role)) { 
       return true; 
      } 
     } 
     return false; 
    } 

} 

而在JavaScript塊這樣使用它:

<script type="text/javascript" th:inline="javascript"> 

    /*[# th:if="${@utilService.hasAnyRole(#httpServletRequest, 'ROLE_ADMIN')}"]*/ 
     ... 
    /*[/]*/ 

</script> 

回答

1

看起來像一個語法錯誤。您的角色名稱在您的sec:authorize="hasAnyRole('ROLE_ADMIN)"沒有結束報價...

+0

的確。我會在今晚晚些時候檢查並通知你。謝謝! – yglodt

+0

Btw一個演示應用程序顯示問題在這裏:https://github.com/yglodt/spring-boot-thymeleaf – yglodt

+0

在演示應用程序中,鏈接「page3」需要認證。 – yglodt

1

我經歷了同樣的問題和 我只需要更新thymeleaf和thymeleaf-extras-springsecurity4幫助。

<properties> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
    <java.version>1.8</java.version> 
    <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version> 
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> 
</properties> 

這裏是a link

相關問題