Spring Security - Redirect if already logged in

To successfully redirect from login page, if user is already logged in, add the following to your login.jsp:

Add a security taglib header to the top of your jsp:

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>

Then add the following tag inside your "head" tag (preferably near the top):

<sec:authorize access="isAuthenticated()">
    <% response.sendRedirect("main"); %>
</sec:authorize>

This will redirect to main.html (or whatever your main .jsp is mapped to) if the user accessing the login page is already logged-in.

Doing this through a controller didn't work for me, since the valid login page practice is to let the spring security's "form-login" bean do all the redirecting work, so there was no login controller for me to modify.


In the controller function of your login page:

  1. check if a user is logged in.

  2. 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";
}