Spring Security - 如果已经登录则重定向 [英] Spring Security - Redirect if already logged in
问题描述
我是 Spring 的新手:
I'm new to Spring:
我不希望经过身份验证的用户访问登录页面.如果用户已通过身份验证,处理/登录"重定向的正确方法是什么?比如说,如果已经登录,我想重定向到/index".
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.
我在登录时尝试过isAnonomous()",但它重定向到访问被拒绝的页面.
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>
推荐答案
在你登录页面的控制器功能中:
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.
相关代码:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
/* The user is logged in :) */
return new ModelAndView("forward:/index");
}
更新
或者在映射可能包含 path variable
的另一种场景中,例如 @GetMapping(path = "/user/{id}")
在这种情况下,您可以实现这个逻辑也是:
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";
}
这篇关于Spring Security - 如果已经登录则重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!