When the root controller ("/") is called, I want to check if the user has authenticated or not. If he is not authenticated I want to display home page while if he is I want to display dashboard like so:
@GetMapping("/")
public String homePage() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null) return "home";
return "dashboard";
}
But when I run the program, it tries to display dashboard, which means that clearly the if() condition returned false. But I know that I definitely did not log in. Why does this not work.
Also, I know I could override the configure(HttpSecurity http) method in the WebSecurityConfigurerAdapter like so:
http.authorizeRequests().antMatchers("/").authenticated();
But this would redirect me to the /login page, which is ok for any other request but not ("/") where I want to be redirected to "home" page if no session exists.
This is the value of authentication after a 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