Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security 3.1 - how to identify user is already logged in or not?

I am using spring security 3.1 for my web application.

I have implemented my custom filter for providing filtering of requested URL.

Once user is logged in and then user hits log in URL, at that time log in URL should not be opened. I mean to say how can I check that user is already logged in or not?

If user is already logged in, log in page should not be opened. It should open default-target-url page.

Thanks.

like image 758
Harshal Patel Avatar asked Feb 22 '23 05:02

Harshal Patel


2 Answers

You can use the static method in the SecurityContextHolder class to get the Security Context from where you can get the Authentication object and then you can find whether a user is currently logged in or not.

like image 65
Samarth Bhargava Avatar answered Feb 23 '23 19:02

Samarth Bhargava


I was looking for a solution to exact same problem. I ended up doing the following:

@RequestMapping(method = RequestMethod.GET, value = "/admin/login")
public ModelAndView login(HttpServletRequest request) {
    Object principal =  SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if(principal instanceof UserDetails && validLogin((UserDetails) principal)){
        return new ModelAndView("redirect:/admin/home"); // Go to admin home if already
                                                         // logged in
    }

    final String error = request.getParameter("login_error");
    return loginPage.display(error); // Not logged in, so admin login page is displayed
}

private boolean validLogin(UserDetails userDetails) {
    // This function does a check to ascertain the validity of the logged in user
    // You may also consider evaluating userDetails.getAuthorities()
    return userDetails.isAccountNonExpired() &&
            userDetails.isAccountNonLocked() &&
            userDetails.isCredentialsNonExpired() &&
            userDetails.isEnabled();
}

But i sure hope there is a more configurable way to achieve this.

like image 25
imdahmd Avatar answered Feb 23 '23 17:02

imdahmd