How to protect your page using WebFilter in JavaEE

This tutorial is to be use in conjunction with picketlink. Normally we want some pages to be accessible only after a user has logged in. In this case we need a real protection filter.

The class below filters a url path and check if there's a logged in user.

package com.czetsuya.listener;


import javax.enterprise.inject.Instance;
import javax.inject.Inject;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.picketlink.Identity;

@WebFilter(urlPatterns = RealmProtectionFilter.REALM_BASE_URI + "/*")
public class RealmProtectionFilter implements Filter {

 public static final String REALM_BASE_URI = "/pages/secured";

 private Instance identityInstance;

 private Identity getIdentity() {
  return this.identityInstance.get();

 public void destroy() {


 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;

  boolean isAuthorized = getIdentity().isLoggedIn();

  if (isAuthorized) {
   chain.doFilter(httpRequest, httpResponse);
  } else {
   forwardAccessDeniedPage(httpRequest, httpResponse);

 private void forwardAccessDeniedPage(HttpServletRequest httpRequest,
   HttpServletResponse httpResponse) throws ServletException,
   IOException {
    .forward(httpRequest, httpResponse);

 public void init(FilterConfig filterConfig) throws ServletException {



The url /pages/secured is validated, if no we redirect to /error/accessDenied.jsf.
How to protect your page using WebFilter in JavaEE How to protect your page using WebFilter in JavaEE Reviewed by Edward Legaspi on Tuesday, September 29, 2015 Rating: 5

No comments:

Powered by Blogger.