30

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>
steve
  • 1,786
  • 1
  • 15
  • 29
  • possible duplicate of [How to redirect to the homepage if the user accesses the login page after being logged in?](http://stackoverflow.com/questions/12597519/how-to-redirect-to-the-homepage-if-the-user-accesses-the-login-page-after-being) – Grzegorz Rożniecki Oct 30 '12 at 08:25
  • http://stackoverflow.com/questions/32225414/spring-security-login-issue-after-re-login-in-same-session/32325358#32325358 This problem is solved on this link.Please take a look – parshant Sep 01 '15 at 07:25

4 Answers4

57

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";
}
Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
Rahul
  • 912
  • 10
  • 18
  • 7
    That will work only for cases like login -> home. What about if I'm already logged in and type the login url in the address bar? It would make sense to get redirected to home page (or wherever I am already are) again... – Aritz Mar 28 '14 at 08:17
8

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.

Milan Vidakovic
  • 436
  • 5
  • 10
3

login.xhtml

<h:head >
    <f:metadata>
      <f:event type="preRenderView" listener="#{loginBean.onPageLoad}"/>
  </f:metadata>
</h:head>

loginBean

public void onPageLoad(){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
yakup_y
  • 155
  • 2
  • 7
2

hey you can do that.

<h:head>
<sec:authorize access="isAuthenticated()">
    <meta http-equiv="refresh" content="0;url=http://your index.xhtml url (full url)" /> 
</sec:authorize>
</h:head>

This method is very simple and convenient, is not it?

erginduran
  • 1,678
  • 5
  • 28
  • 51