Tomcat SecurityFilter和授权

时间:2011-01-28 22:43:50

标签: java authentication tomcat servlet-filters

我已经实现了一个简单的过滤器,只需在当前会话中添加两个原则(参见下面的doFilter)。我的问题是,当我请求资源时,这是触发但是我永远无法看到资源,因为弹出基于FORM的登录屏幕。我试图通过这个特定的过滤器(最终使用快速到期的令牌)绕过基于表单的登录,但似乎似乎没有任何东西允许我这样做。

public void doFilter(ServletRequest request, ServletResponse response,
       FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httprequest = (HttpServletRequest)request;
  HttpServletResponse httpresponse = (HttpServletResponse)response;
  HttpSession session = httprequest.getSession(true);
  Subject subject = (Subject)session.getAttribute("javax.security.auth.subject");

  if (subject == null){
   subject = new Subject();
   PlainUserPrincipal user = new PlainUserPrincipal("admin");
            PlainRolePrincipal role = new PlainRolePrincipal("admin");
   subject.getPrincipals().add(user);
   subject.getPrincipals().add(role);
  }

  chain.doFilter(httprequest, httpresponse);
 }

1 个答案:

答案 0 :(得分:1)

出于安全原因,在运行Tomcat时,无法在/j_security_check的URL模式上映射servlet /过滤器。症状表明你正在这样做。我特意说Tomcat,因为我已经看到它适用于其他(特定)容器品牌/版本的情况。但你不想依赖它。

而是过滤/*,或至少与安全约束相同的URL模式,并拦截用户主体的存在和会话对象的缺失。

if (request.getUserPrincipal() != null && session.getAttribute("subject") == null) {
    Subject subject = new Subject();
    // ...
    session.setAttribute("subject", subject);
}

chain.doFilter(request, response);