Spring mvc 第二节:授权和第二节:身份验证;行不通
我有一个Spring+Thymeleaf项目,其视图代码如下Spring mvc 第二节:授权和第二节:身份验证;行不通,spring-mvc,spring-security,thymeleaf,Spring Mvc,Spring Security,Thymeleaf,我有一个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
<!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>
println语句按预期工作-如果没有用户登录,它将打印“anonymousUser”,否则为用户名
我做错了什么?在将我的应用程序与Thymeleaf&Spring安全演示应用程序进行仔细比较后,我发现了错误的根源 显然,为了让Thymeleaf处理
sec:authorize
和sec:authentication
属性,您需要将springsecuritydial
注册为模板引擎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>
这是令人惊讶的,因为没有提到这一事实。我希望这能帮助将来面临同样问题的其他人。对于java配置版本,添加spring安全方言对我也有帮助:
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new TilesDialect());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
此外,您可能希望在身份验证事件后清除模板缓存,以便使用新的身份验证数据重新处理模板。或者,使用
ServletContextTemplateResolver.setNonCachablePatterns()
将对登录会话敏感的模板设置为非缓存(我就是这么做的),在Spring Boot中,我只需添加以下依赖项:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
也别忘了包括thymeleaf-extras-springsecurity3
maven依赖项,就像我做的那样。这在我没有配置springtemplateenginebean的情况下很有效。我正在使用Spring boot 1.4.1.RELEASE和Spring依赖关系管理插件0.5.1.RELEASE可能的解决方案:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>