如何在 Spring Security 中检查用户是否已登录或匿名

Yee*_*der 5 spring-security spring-boot

当调用根控制器(“/”)时,我想检查用户是否已通过身份验证。如果他没有通过身份验证,我想显示主页,而如果他是,我想像这样显示仪表板:

@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

dur*_*dur 8

您必须禁用匿名身份验证,请参阅HttpSecurity#anonymous

下面演示了如何将匿名用户表示为 null。请注意,这可能会导致NullPointerException假定启用匿名身份验证的代码。

@Configuration
@EnableWebSecurity
public class AnononymousSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
                            .and()
                            // sample anonymous customization
                            .anonymous().disabled();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以检查 class AnonymousAuthenticationToken。您修改后的代码:

@GetMapping("/")
public String homePage() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication instanceof AnonymousAuthenticationToken) return "home";

    return "dashboard";
}
Run Code Online (Sandbox Code Playgroud)