YeetCoder
YeetCoder

Reputation: 354

How to check if user is logged in or anonymous in Spring Security

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

Upvotes: 9

Views: 20299

Answers (3)

cornnutz
cornnutz

Reputation: 125

With the current version of spring security, you could add a role of anonymous authenticated user in the security configuration class; then restrict that role for accessing paths requiring not anonymous.

Upvotes: 0

Yves
Yves

Reputation: 278

Well, the fastest way to do so (worked with me in my app) is the following:

@GetMapping("/")
public Boolean isLoggedIn(Principal principal) {

    if(principal == null) return "home";

    return "dashboard";
}

It should be noted that in my app I already configured all the security stuff. This means that if my solution won't work with you (hope not), know that you have to configure all the security stuff too (check Spring Security courses).

Upvotes: 1

dur
dur

Reputation: 17010

You have to disable anonymous authentication, see HttpSecurity#anonymous:

The following demonstrates how to represent anonymous users as null. Note that this can cause NullPointerException in code that assumes anonymous authentication is enabled.

@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");
    }
}

or you could check for class AnonymousAuthenticationToken. Your modified code:

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

    if (authentication instanceof AnonymousAuthenticationToken) return "home";

    return "dashboard";
}

Upvotes: 15

Related Questions