[英]Spring Security + Thymeleaf - hide specific data from user if not authenticated
我認為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.