While implementing spring security with my GWT based web application. I found that. Everything is working fine as expected, except the below fact:
I opened login.jsp
There is nothing built into Spring Security to prevent you from viewing the login page after logging in. You can block the login page from logged in users by adding the following code to the top of your login page.
<%@ taglib prefix='sec' uri='http://www.springframework.org/security/tags' %>
<sec:authorize ifNotGranted="ROLE_ANONYMOUS">
<% response.sendRedirect("/mainpage.jsp"); %>
</sec:authorize>
The logic is that if the user is not logged in Spring Security will create an anonymous Authentication object for them and provide them with the role of ROLE_ANONYMOUS. So you just check to see if the user has that role, and if they don't you can assume that they are logged in and redirect them to the main page of the application.
Alternatively you can create a Servlet Filter:
public class LoginPageFilter implements Filter
{
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if(request.getUserPrincipal() != null){ //If user is already authenticated
response.sendRedirect("");// or, forward using RequestDispatcher
} else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
public void destroy() {
}
}
web.xml:
LoginPageFilter com.xxx.xx.LoginPageFilter
<filter-mapping>
<filter-name>LoginPageFilter</filter-name>
<url-pattern>/login</url-pattern>
</filter-mapping>