Spring Security - Redirect if already logged in

前端 未结 4 1148
-上瘾入骨i
-上瘾入骨i 2020-12-05 06:58

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 alr

4条回答
  •  既然无缘
    2020-12-05 07:45

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

提交回复
热议问题