11.7. Allowing a User to Log in Automatically
Problem
You want to allow users to be logged in automatically if they have valid credentials stored in a cookie(s).
Solution
Use a servlet filter, such as the one shown in Example 11-12, that looks for cookies containing the user's credentials. The credentials are used to authenticate the user. If the authentication succeeds, the user is automatically logged in; otherwise, the user will be prompted to login.
Example 11-12. Cookie authentication filter for automatic login
package com.oreilly.strutsckbk.ch11; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Filter which handles application authentication. The filter implements * the following policy: * <ol> * <li>If the username is in the session the filter exits; * <li>If not, the authentication cookies are looked for; * <li>If found, the authentication is attempted * <li>If authentication is successful, the username is stored in * the session * <li>Otherwise, the cookies are invalid and subsequently removed * from the response * </ol> * * @author Bill ...
Get Jakarta Struts Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.