java - Spring Security + Thymeleaf - 如果未通过身份验证,则对用户隐藏特定数据
问题描述
我认为 Thymeleaf 不知道用户何时登录,我已经向经过身份验证<a>
的用户隐藏了两个标签,但它们仍然显示。
pom.xml:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
这是问题的代码 - 对经过身份验证的用户隐藏两个锚标记:
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
...
...
<div sec:authorize="isAnonymous()">
<a th:href="@{/login}">Log in</a>
<br>
<a th:href="@{/register}">Register</a>
</div>
<br>
<a th:href="@{/recipeList}">List Page</a>
即使在我登录后,我仍然看到“登录”和“注册”标签
这是配置,如果它有用的话:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public DataSource dataSource;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception{
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(dataSource);
return jdbcUserDetailsManager;
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/register").permitAll()
.antMatchers("/recipeList").permitAll()
.antMatchers("/foodDescription/**").permitAll()
.antMatchers("/addNew/**").hasAnyRole("ADMIN","USER")
.antMatchers("/delete/**").hasRole("ADMIN")
.antMatchers("/edit/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/").permitAll();
http.csrf().disable();
}
}
我的猜测是 Thymeleaf 不知道用户何时登录,如果我的代码需要任何其他类,我将对其进行编辑。现在一直被困在这上面。
解决方案
我假设您使用的是 Spring Boot 2.1.x
然后你必须使用版本 5:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
推荐阅读
- angular - 由于经常更改数据,单击角度材料表效果不佳
- r - Gsub 到 gsubfn,它是如何传输的?
- c# - C#用OpenXML中的图像替换文本持有者导致文件损坏
- oracle - 如何在存储过程中使用替换
- python - Python - 数组索引,为什么需要双括号
- algorithmic-trading - 在 MQL4 中使用带有“OR”运算符的多个条件时,订单关闭和打开非常迅速
- postgresql - 有没有办法用 pgpromse 查看限制偏移查询是否已经结束?
- scala - 使用 Apache Spark 将带有 JSON 字符串的 DF 保存为不带转义字符的 JSON
- c# - 无法连接远程机器上的rabbitmq服务器(windows服务器)
- jmeter - JMS - 项目不会出队列