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 InstanceidentityInstance;
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.
0 nhận xét:
Đăng nhận xét