Using servlet filters for user authentication
When creating a Java web application that requires access restrictions on some pages, one way to do it is to include user authentication logic within each JSP, or perhaps in a JSP fragment that is included in all of these JSPs. In that code perform a redirect or forward to an access denied page.
1 | req.getRequestDispatcher( "/accessDenied.html" ).forward(request, response); |
However, a Java web container is multi-threaded, and this merely spawns a new thread, and the server processes both the JSP and the page that has been forwarded to simultaneously. If one looks at the logging output from the server, or intercepts the HTTP traffic, using, for example, a packet sniffer (which are commonplace enough to exist as Firefox extensions), one can see this happening live. This method therefore, clearly raises some nasty security concerns.
Furthermore, from a software engineering or architectural design point of view, using a JSP as a filter violates MVC design principles, as doing so would make the JSP act as a controller as well as a view at the same time.
The proper way to go about implementing restricted access to certain pages is to use filters from the Servlet API, and then configuring the web application to map select pages to these filters. This method utilises additional capability provided by web container that runs on the server. The web container constructs filter chains based on the filter mappings defined. Most crucially, these filters allow the authentication logic and consequent branching to be executed prior to the JSP being called;
Create an abstract class `LoginFilter`.
01 | public abstract class LoginFilter implements javax.servlet.Filter { |
02 | protected ServletContext servletContext |
04 | public void init(FilterConfig filterConfig) { |
05 | servletContext = filterConfig.getServletContext(); |
09 | ServletRequest request, ServletResponse response, FilterChain chain) |
10 | throws IOException, ServletException { |
11 | HttpServletRequest req = (HttpServletRequest)request; |
12 | HttpServletResponse resp = (HttpServletResponse)response; |
15 | resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); |
20 | chain.doFilter(request, response); |
24 | * logic to accept or reject access to the page, check log in status |
25 | * @return true when authentication is deemed valid |
27 | protected abstract boolean isAuth(); |
Subclass the `LoginFilter` as a concrete class, `MemberLoginFilter`, by implementing the `isAuth` method. In this case add logic that determines whether a user is currently logged in. This post does not cover how this is done; in a nutshell, this would typically involve retrieving objects from the current HTTP session, and determining whether a user has logged in during the current session by comparing the values or states of these objects.
Now edit the `web.xml` configuration for the web application archive (WAR), to make the web app aware of the filter and what pages it should map to.
2 | < description >Requires user to log in as a memberdescription > |
3 | < filter-name >MemberLoginFilterfilter-name > |
4 | < filter-class >some.package.MemberLoginFilterfilter-class > |
7 | < filter-name >MemberLoginFilterfilter-name > |
8 | < url-pattern >/someRestrictedPage.jspurl-pattern > |
Add as many filter mappings as necessary for each page that needs to have access to it restricted to logged-in members only; use file name globs to match multiple files.
Also, still editing `web.xml` configuration, tell the web app how to handle access denied error messages in a more user friendly way, by adding the following node to the settings:
2 | < error-code >401error-code > |
3 | < location >/accessDenied.htmllocation > |
The HTTP 401 error code referenced here corresponds to `HttpServletResponse.SC_UNAUTHORIZED` in `LoginFilter.doFilter(..)`.
This completes the loop: when the filter chain is broken because `LoginFilter.isAuth()` returns false, instead of getting a garish HTTP 401, the user will see an access denied page instead, which you can edit to inlcude a user friendly message.
If `LoginFilter.isAuth()` returns true, the filter chain continues execution, and assuming that there are no more filters in the filter chain, or all of the downstream filters in the filter chain pass, the requested JSP or servlet gets displayed.
No comments:
Post a Comment