当调用根控制器(“/”)时,我想检查用户是否已通过身份验证。如果他没有通过身份验证,我想显示主页,而如果他是,我想像这样显示仪表板:
@GetMapping("/")
public String homePage() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null) return "home";
return "dashboard";
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行程序时,它尝试显示仪表板,这意味着if() 条件显然返回 false。但是我知道我肯定没有登录。为什么这不起作用。
另外,我知道我可以像这样覆盖 WebSecurityConfigurerAdapter 中的 configure(HttpSecurity http) 方法:
http.authorizeRequests().antMatchers("/").authenticated();
Run Code Online (Sandbox Code Playgroud)
但这会将我重定向到 /login 页面,这对于任何其他请求都可以,但如果没有会话存在,我想重定向到“主页”页面(“/”)。
这是 Sysout 后身份验证的值: org.springframework.security.authentication.AnonymousAuthenticationToken@52132976: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS