我正在使用 Spring Core 版本 4.1.6 和 Spring security 4.0.1。
我想在超时时将用户重定向到登录页面。
到目前为止,经过一些研究,我实现了 ApplicationListener<HttpSessionDestroyedEvent>
我现在可以成功拦截超时和注销。
我有HttpSessionDestroyedEvent
onApplicationEvent
中的对象功能。该对象似乎没有任何可以重定向用户或返回登录模型对象的方法。我的问题是如何将用户重定向到登录页面?
我见过this url但它不会拦截超时。我的问题更集中于超时。
最佳答案
有几种方法可以实现这一点。首先,您可以通过设置 login-page
在 applicationContext.xml
中使用 spring security 自动配置,它会自动重定向未登录的用户到达安全路由(例如/userReged/* *) 到某个登录页面:
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
<security:intercept-url pattern="/userReged/**" access="ROLE_USER"/>
<security:form-login
login-page="/"
default-target-url="/somePage"
authentication-failure-url="/user/logfailed?error"
username-parameter="userName"
password-parameter="userPassword" />
<security:logout
logout-success-url="/?logout"/>
</security:http>
另一种方法是检查用户在特定路径中手动登录 Controller :
@RequestMapping("/somePage")
public String getSomePage(Model model, HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
if (principal != null) {
User activeUser = userService.getUserByPhone(principal.getName());
// ...
} else { // user is not authenticated
System.out.println("user is not authenticated to proceed the somePage!!!!!!!");
return "redirect:/";
}
}
为了设置 Spring Security 的超时,您可以将其放入 web.xml
中:
<session-config>
<session-timeout>
1440
<!--mins-->
</session-timeout>
</session-config>
现在,如果您想在精确的超时时间内重定向客户端,您可以在客户端以一定的时间间隔自动刷新页面。
关于java - Spring Security 超时时将用户重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812484/