2011-12-01 33 views
3

简短问题。在执行任何声明式安全检查之前,如何执行servlet过滤器?Servlet过滤器(自动登录)优先于声明性安全检查

长问题。对于我的Web应用程序,我试图使用服务器声明式安全来管理我所有的安全需求:我已设置<url-pattern>/secure/*</url-pattern><auth-method>FORM</auth-method><form-login-page>/sign-in.xhtml</form-login-page>的安全约束。

为了提供一个基于cookie的“记住我”功能,我设置了一个servlet过滤器,它拦截每个请求,检查用户是否未登录,检查他是否可以自动登录cookie),最终将他记录为使用基于servlet的登录。

<filter-mapping> 
    <filter-name>CustomLoginFilter</filter-name> 
    <url-pattern>*.xhtml</url-pattern> 
</filter-mapping> 

现在,如果用户打开他的浏览器并连接到mysite.com一切正常。但是,如果用户打开他的浏览器,使像我mysite.com/secure/secret.xhtml遵守以下行为直接要求的东西:

  1. GET /secure/secret.xhtml
  2. 数in.xhtml的支持Bean实例化( FacesContext的可用)
  3. 的CustomLoginFilter.doFilter()被调用,(FacesContext的是NULL)

这显然阻碍了全部过程。我找不到通过服务器“声明式安全过滤器”(或其他)给我的CustomLoginFilter优先的方法;更改声明的web.xml顺序不会帮助太...任何想法?谢谢!

回答

3

在执行任何声明性安全检查之前如何执行servlet过滤器?

由于规范和安全限制,这是不可能的。

最好的办法就是登录页面上的preRenderView事件挂钩,并使用新的Servlet 3.0 HttpServletRequest#login()方法进行编程式登录。

E.g.

<f:event type="preRenderView" listener="#{authenticator.checkAutoLogin}" /> 

的东西,如

public void checkAutoLogin() throws IOException { 
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); 
    Cookie autoLogin = externalContext.getRequestCookieMap().get("autoLoginCookieName"); 

    if (autoLogin != null) { 
     User user = decryptCookieValueAndExtractUser(autoLogin.getValue()); // Yes, it must be encrypted! Otherwise a too easy hack. 

     if (user != null) { 
      HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); 

      try { 
       request.login(user.getName(), user.getPassword()); 
       String originalRequestURI = externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI); 
       externalContext.redirect(originalRequestURI != null ? originalRequestURI : "someDefaultIndex.xhtml"); 
      } catch (ServletException e) { 
       // Login failed. It's up to you how to handle it. 
      } 
     } 
    } 
} 
+0

是,'#HttpServletRequest的登录()'已经是基本的登录方法。谢谢,这是一个很好的建议,可能是避免限制简单的唯一方法。 *我想借此机会亲自感谢您提供的所有优质答案和文章(我在前几周已经从他们那里学到了很多)!! * – Fabio

+0

欢迎您:) – BalusC