【问题标题】:How to restrict unauthorized user to access page directly in jsf如何限制未经授权的用户直接在jsf中访问页面
【发布时间】:2014-03-03 12:46:20
【问题描述】:

如果用户未经授权,我试图限制用户访问任何页面。我正在使用 jsf 2.2 和 primefaces。以下是我的代码:

我的过滤器

@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        try {


            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            HttpSession session = request.getSession(false);

            String user = (session != null) ? session.getAttribute("username")
                    .toString() : null;

            String loginURL = request.getContextPath() + "/ldapLogin.xhtml";
            boolean loginRequest = request.getRequestURI().startsWith(loginURL);
            boolean resourceRequest = request.getRequestURI().startsWith(
                    request.getContextPath()
                            + ResourceHandler.RESOURCE_IDENTIFIER);
            if (user != null || loginRequest) 
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath()
                        + "/ldapLogin.xhtml");
            }

        } catch (Throwable t) {
            System.out.println(t.getMessage());
        }
    } 

当我的会话未验证或我尝试直接访问页面但无法重定向到 ldapLogin.xhtml

时,我的控件进入 else 条件

Web.xml

<context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>ApplicationResources</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
    <param-value>en</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
             /WEB-INF/applicationContext-dao.xml,
             /WEB-INF/springLdap-security.xml
        </param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>
            /WEB-INF/taglibs/acegijsf.taglib.xml
        </param-value>
  </context-param>
  <context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>bootstrap</param-value>
  </context-param>
  <context-param>
    <param-name>org.omnifaces.FACES_VIEWS_SCAN_PATHS</param-name>
    <param-value>/*.xhtml</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>faces</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>faces</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
  <welcome-file>ldapLogin.xhtml</welcome-file>

LoginLdap.java

public String ldapLoginAuthentcator() {
        if (contact != null) {
            HttpSession session = FilterUtil.getSession();
            session.setAttribute("username", user.getName());
            return "success";
        } else {
FacesContext.getCurrentInstance().addMessage(null,
    new FacesMessage(FacesMessage.SEVERITY_WARN,"Invalid Login!", "Please TryAgain!"));
            return "login";
        }

终于FilterUtil.java

public class FilterUtil {

      public static HttpSession getSession() {
   return(HttpSession)FacesContextgetCurrentInstance().getExternalContext().getSession(true);
      }

}

我不知道问题出在哪里,但是当我尝试访问页面时,即使我已获得授权或我的会话未经过验证,但我仍然可以访问该页面。任何帮助都会被挪用。当前所有页面都与未放置在 web-inf 文件夹中的 public 位于同一根路径中。

更新:

当我尝试在没有有效会话的情况下直接访问页面时,例如,如果我尝试访问 http://192.35.36.178:8042/SOW/start 并且它进入我的过滤并成功过滤但没有发生重定向,当我尝试使用 firebug 检查它时它重定向到某个不同的星球。它实际上重定向到

 "http:172.36.98.658//8042/SOW/javax.faces.resource/theme.css.xhtml?ln=primefaces-bootstrap"

状态为 302 Found 而不是重定向到 response.sendRedirect(request.getContextPath()+ "/ldapLogin.xhtml") 以及当我尝试检查 contextPath 它的显示 /sow

【问题讨论】:

  • @Makky 感谢您的及时回复,实际上我是 jsf 的新手,我曾在 struts2 上工作,但出于项目要求,我们需要实现此安全性。但是,除了转移到 PhaseListener 之外,我还想知道这个过滤器有什么问题,以及为什么当用户不是有效用户时它没有被重定向到 login.xhtml?以及如果您有 PhaseListener 的一些工作代码,那么我想试一试。
  • 好的...你的意思是这个过滤器不适用于ajax调用,那么请提前分享一些工作代码..thanx
  • 您能否确认重定向请求(302)实际上正在返回到浏览器并且正在请求适当的 URL?
  • @kolossus 请检查更新,

标签: jsf jsf-2 servlet-filters


【解决方案1】:

我将向您展示我如何在不使用 Filter 或 PhaseListener 的情况下做到这一点。

如果您使用模板最好的方法,然后将此行放在模板的正文中,或者(如果没有模板)在您要限制访问的每个页面中:

<f:event type="preRenderView" listener="#{yourBean.checkPermissions}"/>

在模板中:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
<h:head>
    <meta charset="UTF-8" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <h:outputStylesheet name="stylesheet.css"/>    
    <title>${pageTitle}</title>
    <meta http-equiv="keywords" content="${metaKeywords}" />
    <meta http-equiv="description" content="${metaDescription}" />
</h:head>

<body>
<f:event type="preRenderView" listener="#{yourBean.checkPermissions}"/>
...

在你的 Bean 中添加如下监听方法:

    public void checkPermissions(ComponentSystemEvent event) {

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession httpSession = (HttpSession)(fc.getExternalContext().getSession(false)); 
        String cid = (String) httpSession.getAttribute(AttributeName.ADMINISTRATOR_CLIENT_LOGIN_ID);
        if( cid == null){
            ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler)fc.getApplication().getNavigationHandler();
            handler.performNavigation(this.navi.getClientLogin().getLink());
            return;
        }
        ....
        ....
    }

更新:一个使用过滤器的工作示例(我使用 JSF2.2 Mojarra 2.2、Tomcat 7 对其进行了测试):

在您的 web.xml 中编辑/添加/:

....
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>


....

这是一个示例过滤器实现:

import java.io.IOException;

import javax.faces.application.ResourceHandler;
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 javax.servlet.http.HttpSession;

@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        try {
            System.out.println("doFilter ...");
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            HttpSession session = request.getSession(false);
            String user = (session != null) ? (String)session.getAttribute("username") : null;
            String loginURL = request.getContextPath() + "/ldapLogin.xhtml";
            boolean loginRequest = request.getRequestURI().startsWith(loginURL);
            boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath()+ ResourceHandler.RESOURCE_IDENTIFIER);
            if (user != null || loginRequest) {
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/ldapLogin.xhtml");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        //      
    }
}

【讨论】:

  • &lt;f:viewAction/&gt; 在 JSF2.2 中更可取
  • 虽然这可能有效,但这是不是推荐的方法。过滤器是。即能够覆盖非JSF请求。
  • @kolossus,谢谢,你的建议是正确的,因为我是从一个旧项目中复制的,我专注于这个想法而不是细节。
  • @BalusC:首先,我要感谢您在 SO 上发表的所有精彩帖子。现在到我的答案,这将完美地工作(当然只有JSF),我建议在过滤器上使用它,因为上面的问题中存在这样的问题。无需处理不需要限制的所有页面上的所有请求,重定向没有问题...等,无需检查 response.isCommitted() 是否...等。
  • @Rami.Q 感谢您的建议...但我在这里是为了解决我的问题,您知道为什么当我尝试直接访问时它没有重定向到登录页面。
猜你喜欢
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2011-10-15
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多