6

I want to restrict access to certain JSF pages based on user access rights. How to do it in JSF ? I have found two links: Restricting users from accessing pages by directly changing the URL in JSF. But the answer didn't mention how to block access to page. With response.sendError ? The second link: JSF: How control access and rights in JSF?

Also what is the best to use PhaseListener or to use ServletFilter ?

Community
  • 1
  • 1
John N
  • 844
  • 4
  • 12
  • 20

1 Answers1

8

But the answer didn't mention how to block access to page. With response.sendError ?

It's fully to your choice. It all depends on your business requirements. Do you want to redirect to login page? Just do that!

response.sendRedirect(request.getContextPath() + "/login.xhtml");

Or, do you want to show a scary and user-unfriendly HTTP 401 error? Just do that!

response.sendError(HttpServletResponse.SC_UNAUTHORIZED);

At least, anything but continuing the request to the restricted resource by chain.doFilter(). Otherwise the whole restriction would be pointless.


Also what is the best to use PhaseListener or to use ServletFilter ?

A servlet filter is designed to intercept on HTTP requests and runs only once far before FacesServlet is invoked and is therefore capable of hooking on non-JSF requests, depending on the URL pattern.

A phase listener is designed to intercept on before- and after-condition of every single JSF phase (there are 6) and runs 2 up to 12 times during a JSF request, depending on the current JSF phase.

What does your common sense say? Which one looks more simple and efficient for the very simple job of allowing/blocking HTTP requests (and thus not JSF phases)? Just use the right tool for the job.


For case you're interested, here's a rather complete example of such an authorization filter: Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you for your answer! I will try to use WebFilter-Pattern. If I understand correctly WebFilter will be called on every user request for HTML or AJAX before FacesServlet. My problem is that I don't understand good the Java-API for Web (servlet): /redirect /forward etc. Can I use resp.sendError for redirecting the url to restricted source. – John N Aug 22 '13 at 23:43
  • 2
    Use `response.sendRedirect()` to redirect. To learn more about basic filters and servlets, see also http://stackoverflow.com/tags/servlet-filters/info and http://stackoverflow.com/tags/servlets/info – BalusC Aug 22 '13 at 23:48
  • You provide very nice examples for my question! Thank you! – John N Aug 22 '13 at 23:57