2011-09-06 83 views
0

我有一个简单的用例,我想在会话开始时获取会话变量,并且只允许根据结果访问某些页面。我不是很清楚这是最好的使用bindInterceptor拦截任何页面上的任何@Get或@Post方法或使用过滤器更好。这里是想我做的,但草图很开放的替代品:bindInterceptor vs过滤器的guice安全性?

At the start of a new session (@SessionScoped ?), check a session variable authentication token 

If (authentication == admin) { 
    serveRegex("admin/(jsp|html)/.*").with(GuiceContainer.class); //only allow /admin subpages 
    req.getRequestDispatcher("/admin").forward(req, res); //fwd all initial page requests to /admin 
} 
else If (authentication == user) { 
    serveRegex("user/(jsp|html)/.*").with(GuiceContainer.class); //only allow /user subpages 
    req.getRequestDispatcher("/user").forward(req, res); //fwd all initial page requests to /user 
} 
else { 
    serveRegex("signin/(jsp|html)/.*").with(GuiceContainer.class); //only allow /signin subpages 
    req.getRequestDispatcher("/signin").forward(req, res); //fwd all initial page requests to /signin 
} 

哪些技术是一种用于管理该安全模型的首选方法(至少代码,最快的速度,等等)?我很想看到一个示例项目。

感谢您的帮助!

-John

回答

1

这样做的常用方法是使用过滤器。鉴于您似乎将URI空间分隔为不同的所需权限,这也可能是最简单的方法。如果你想在方法/类(“@AdminRequired”等)上声明认证逻辑,但是确实没有理由这么做,那么bindInterceptor风格很有用 - 分离URI空间更容易。

只需绑定一个获取当前用户/授权逻辑的过滤器,并检查权限是否与请求将发往的URI相匹配。

例如

class AuthenticationFilter implements Filter { 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { 
    User user = getUserSomehow(); 
    if (user == null) { 
     response.sendRedirect(... login page ...); 
     return; 
    } 
    if (request.getRequestURI().startsWith("/admin")) { 
     // Enforce Admin login, error out otherwise. 
    } 
    // Proceed with executing the request. 
    chain.doFilter(request, response); 
    } 
} 

请注意,您必须将ServletRequest/Response下传到HttpServletRequest/Response。