Duš*_*ský 19 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://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>
Run Code Online (Sandbox Code Playgroud)
sec:authorize和sec:身份验证属性不能按预期工作 - 即使没有用户登录,也始终显示div,并且span始终显示为"miquel".
跟随我的控制器类的相关片段.
@RequestMapping(value = "/welcome.html")
public String wellcome() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("username: " + auth.getName());
return "home";
}
Run Code Online (Sandbox Code Playgroud)
println语句按预期工作 - 如果没有用户登录,则打印"anonymousUser",否则输出用户名.
我究竟做错了什么?
Duš*_*ský 24
在将我的应用程序与Thymeleaf和Spring Security演示应用程序紧密比较后,我发现了错误的来源.
显然,为了让Thymeleaf处理sec:authorize和sec: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>
Run Code Online (Sandbox Code Playgroud)
这是令人惊讶的,因为在相关的Thymeleaf文档页面上没有提到这一事实.我希望这有助于将来面临同样问题的其他人.
Jan*_*Gun 16
在Spring Boot中,我只需要添加以下依赖项:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
小智 6
对于java配置版本,它通过添加spring安全方言也适用于我:
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new TilesDialect());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21032 次 |
| 最近记录: |