如何用isAuthenticated()和isAnonymous()控制导航链接显隐?解决方法恒真问题
问题:Spring Security与Thymeleaf集成时,
isAuthenticated()和isAnonymous()始终返回true 我最近碰到一个棘手的问题:想在导航栏实现用户登录时显示MyProfile,匿名状态时显示MyAccount的逻辑,但不管用户是否登录,isAuthenticated()和isAnonymous()这两个方法始终都返回true,导致两个导航元素同时显示,完全达不到预期效果。
相关代码片段
header.xml(Thymeleaf模板)
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> <!-- 其他代码 --> <ul class="navbar-nav ml-auto"> <li><a class="nav-link" href="#" style="color: black">Shopping Cart</a></li> <li sec:authorize="isAnonymous()"><a th:href="@{/login}" class="nav-link" style="color: black"> My Account </a></li> <li sec:authorize="isAuthenticated()"><a th:href="@{/myProfile}" class="nav-link" style="color: black"> My Profile </a></li> </ul>
SecurityConfig.java(Spring Security配置)
// 其他代码 private static final String[] PUBLIC_MATCHERS = { "/css/**", "/js/**", "/images/**", "/", "/myAccount", "/forgetPassword", "/newUser", "/login" }; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated(); http.csrf().disable().cors().disable().formLogin().failureUrl("/login?error").defaultSuccessUrl("/") .loginPage("/login").permitAll().and().logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/?logout") .deleteCookies("remember-me").permitAll().and().rememberMe(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder()); }
pom.xml(依赖配置)
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>2.1.3.RELEASE</version> </dependency>
尝试过的无效方案
- 更换
thymeleaf-extras-springsecurity的同系列版本(比如调整2.1.3.RELEASE到其他4.x分支版本) - 修改Thymeleaf模板中的
sec命名空间地址
最终解决方案
把pom.xml中的Spring Security Thymeleaf扩展依赖的artifactId从thymeleaf-extras-springsecurity4改成thymeleaf-extras-springsecurity5,问题就彻底解决了!修改后的示例依赖如下:
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> <!-- 可根据你的Spring版本选择匹配的版本 --> </dependency>
事后复盘发现,核心原因是Spring Security版本与Thymeleaf扩展版本不兼容——我当时使用的是Spring Security 5.x版本,但错误搭配了对应Spring Security 4的Thymeleaf扩展,导致权限判断的方法无法正常识别用户状态。
内容的提问来源于stack exchange,提问作者Francesco31
相关产品推荐
相关产品推荐

