I have project (Java, JSF) and I need a way to redirect to login.xhtml page after idle time (inactive)
what should I add to my code ?
I have project (Java, JSF) and I need a way to redirect to login.xhtml page after idle time (inactive)
what should I add to my code ?
Two concepts that already exist and work together:
Tomcat recognizes an authenticated connection by a session cookie. If that cookie is missing or contains an invalid value, and the web application declares security constraints in web.xml the container (Tomcat?) will automatically force the user to login. This may happen via an application-provided login page. How to add Security Constraint in web.xml file?
If the application declares that a session should expire after some time the container will simply invalidate the session when there was no activity. Furthe requests come in as unauthenticated and will be redirected to the login page. Default session timeout for Apache Tomcat applications
Even though I sent references to Tomcat, the definitions need to be done in web.xml and will get effective on any compliant servlet container.
So ensure your web.xml file contains these snippets:
<security-constraint>
<web-resource-collection>
<web-resource-name>restricted methods</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
<session-config>
<session-timeout>30</session-timeout><!-- 30 minutes -->
</session-config>
I Solve my problem by adding JavaScript on each page except login page, I set it the timeout 15 minutes then redirect to login page and call logout function automatically.
<script>
var time = new Date().getTime();
document.onmousemove = function(event) {
time = new Date().getTime();
}
document.onkeypress = function() {
time = new Date().getTime();
}
function refresh() {
if (new Date().getTime() - time >= 900000) {
document.getElementById("hiddenForm:gotoRegButton").click();
alert("Session expired please login again");
location.href = '../../../login/';
} else {
setTimeout(refresh, 900000);
}
}
setTimeout(refresh, 1000);
</script>
<h:form id="hiddenForm" style="display: none;">
<h:commandButton id="gotoRegButton"
action="#{mbLogin.logout()}" >
<f:ajax execute="@form" render="statsData" />
</h:commandButton>
</h:form>
And for prevent accessing any another page when login flag is false, I added a below function on each page which checks the login flag before go to requested URL.
@PostConstruct
/////////////////////////////////////////////////////
public void checkLoginFlag() {
boolean loginFlag = LoginController.loginFlag;
if (!loginFlag) {
redirect("../../login");
}
}