no

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 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 java.io.IOException;

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";

 @Inject
 private Instance identityInstance;

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

 @Override
 public void destroy() {

 }

 @Override
 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 {
  httpRequest.getServletContext()
    .getRequestDispatcher("/error/accessDenied.jsf")
    .forward(httpRequest, httpResponse);
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {

 }

}

The url /pages/secured is validated, if no we redirect to /error/accessDenied.jsf.

Related

java 1905915440274092006

Post a Comment

item