11.6. Ensuring Security Across Your Entire Application
Problem
You need to verify the user is logged in and authenticated when a request is received for any URL path of your web application.
Solution
Use an
authentication servlet filter,
such as the one in Example 11-10, which checks for a
User
object in the session.
Example 11-10. A servlet filter that checks if the user is logged in
package com.oreilly.strutsckbk.ch11.ams; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class AuthenticationFilter implements Filter { private String onFailure = "logon.jsp"; private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; onFailure = filterConfig.getInitParameter("onFailure"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // if the requested page is the onFailure page continue // down the chain to avoid an infinite redirect loop if (req.getServletPath( ).equals(onFailure)) { chain.doFilter(request, ...
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.