Spring Security - Redirect if already logged in

spring, spring-security

Solution

In the controller function of your login page:

check if a user is logged in.

then forward/redirect him to the index page in that case.

Relevant code:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if (!(auth instanceof AnonymousAuthenticationToken)) {

    /* The user is logged in :) */
    return new ModelAndView("forward:/index");
}

Update

Or in another scenario where the mapping may be containing `path variable` like `@GetMapping(path = "/user/{id}")` in this case you can implement this logic as well:

@GetMapping(value = "/login")
public String getLogin() throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!(auth instanceof AnonymousAuthenticationToken)) {
        User loggedInUser = userService.findByEmail(auth.getName())
                    .orElseThrow(Exception::new);
        /* The user is logged in :) */
        return "redirect:/user/" + loggedInUser.getUserId();
    }
    return "login";
}

Problem

I'm new to Spring: I do not want authenticated user from accessing the login page. What is the proper way to handle redirects for the '/login' if the user is already authenticated? Say, I want to redirect to '/index' if already logged in. I have tried 'isAnonomous()' on login, but it redirects to access denied page. ``` <security:http auto-config="true" use-expressions="true" ...> <form-login login-processing-url="/resources/j_spring_security_check" default-target-url="/index" login-page="/login" authentication-failure-url="/login?login_error=t" /> <logout logout-url="/resources/j_spring_security_logout" /> ... <security:intercept-url pattern="/login" access="permitAll" /> <security:intercept-url pattern="/**" access="isAuthenticated()" /> </security:http> ```

Original source

Related problems