如何在百里香的表达中使用sec:[something]?

Die*_*gun 7 spring-security thymeleaf

我知道如何在自己的HTML标签上使用sec:authentication="name"sec:authorize="hasAnyRole(...)"生成结果,但现在我想在表达式中使用它们,例如:

th:if="${hasAnyRole('ROLE_USER', 'ROLE_ADMIN') and someotherboolexpression}"
Run Code Online (Sandbox Code Playgroud)

有办法做到这一点吗?

Bnr*_*rdo 13

使用thymeleaf-extras-springsecurity模块,你可以使用Spring Security的授权表达式中th:if使用#authorization的表达工具的对象.

<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')') and #authorization.expression('...') }">
    This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>
Run Code Online (Sandbox Code Playgroud)

实际上,这个新模块添加的方言sec用作默认前缀,因此您可以使用sec:authenticationsec:authorize好像使用标记库一样.

<div sec:authorize="hasRole('ROLE_ADMIN')">
    This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>

<div sec:authentication="name">
    The value of the "name" property of the authentication object should appear here.
</div>
Run Code Online (Sandbox Code Playgroud)

您所要做的就是将方言添加到模板引擎配置中

<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
    ...
    <property name="additionalDialects">
        <set>
            <!-- Note the package would change to 'springsecurity3' if you are using that version -->
            <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
        </set>
    </property>
    ...
</bean>
Run Code Online (Sandbox Code Playgroud)

  • @Bnrdo如何使用java类做同样的事情? (5认同)