sec:authorize和sec:authentication注释不起作用


问题内容

我有一个带有以下视图代码的Spring + Thymeleaf项目。

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>
    <title>Contacts</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="content">
    <h1>Welcome to the site!</h1>
    <p th:if="${loginError}">Wrong user or password</p>
    <form th:action="@{/j_spring_security_check}" method="post">
        <label for="j_username">Email address</label>:
        <input type="text" id="j_username" name="j_username"/> <br/>
        <label for="j_password">Password</label>:
        <input type="password" id="j_password" name="j_password"/> <br/>
        <input type="submit" value="Log in"/>
    </form>
</div>

<div sec:authorize="isAuthenticated()">
    User: <span sec:authentication="name">miquel</span>
</div>
</body>
</html>

sec:authorize和sec:authentication属性无法正常工作-即使没有用户登录,div也会始终显示,并且跨度始终显示为“
miquel”。

遵循我的控制器类中的相关片段。

@RequestMapping(value = "/welcome.html") 
public String wellcome() { 
    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
    System.out.println("username: " + auth.getName());

    return "home"; 
}

println语句按预期方式工作-如果没有用户登录,则打印“ anonymousUser”,否则显示用户名。

我究竟做错了什么?


问题答案:

在将我的应用程序与Thymeleaf&Spring Security演示应用程序进行了紧密比较之后,我发现了错误的根源。

显然,为了让Thymeleaf处理sec:authorizesec:authentication属性,您需要注册SpringSecurityDialect为模板引擎bean的其他方言。

<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
    <property name="additionalDialects">
        <set>
            <bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" />
        </set>
    </property>
</bean>

令人惊讶的是,在相关的Thymeleaf文档页面上没有提及该事实。我希望这对将来会遇到相同问题的其他人有所帮助。