开发者

bindInterceptor vs filter for guice security?

开发者 https://www.devze.com 2023-04-03 14:12 出处:网络
I have a simple use case where I want to grab a session variable at the beginning of the session and only allow access to certain pages based on the result.I\'m not real clear on is this best accompli

I have a simple use case where I want to grab a session variable at the beginning of the session and only allow access to certain pages based on the result. I'm not real clear on is this best accomplished using bindInterceptor to intercept any @Get or @Post method on any page or is it better to use a filter. Here is a sketch of what I'd like to do but am open to alternatives:

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
}

Which technique is the preferred开发者_开发百科 approach (least code, fastest, etc) for managing this security model? I'd love to see an example project.

Thanks for your help!

-John


The common way of doing this is using a Filter. Given that you seem to segregate your URI space for the different required permissions, that's also probably the easiest way. A bindInterceptor style is useful if you want the authentication logic declared on the methods/classes ("@AdminRequired" or such), but there's really no good reason to do that - segregating the URI space is easier.

Just bind a Filter that gets the current user/authorization logic and checks whether the permissions match the URI the request is going to.

E.g.

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);
  }
}

Note that you'll have to down-cast the ServletRequest/Response to HttpServletRequest/Response.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号