Is there any easy way to preprocess and redirect GET requests?
Asked Answered
S

1

12

I'm looking for a best practise answer. I want to do some preprocessing for GET requests. So e.g. if the user is not allowed to see the page, redirect him to another page. But I don't want to use normal servlet filter, because I would like to express this behavior in the faces-config.xml. Is this possible and how is that called, how can it be done?

Can I define some Filter bean that also returns a String telling the faces-config.xml where to go next?

I googled for this but only hit on the normal filters. If I use filters, can a @WebFilter be a @ManagedBean at the same time? Or is that bad style?

Spicer answered 3/9, 2011 at 17:21 Comment(0)
D
20

If you're homegrowing HTTP request authentication on top of JSF, then a servlet filter is really the best approach. JSF is "just" a MVC framework and nothing in the JSF API is been specified to filter incoming HTTP requests to check user authentication. On normal GET requests, a JSF managed bean is usually only constructed when the HTTP response is about to be created and sent, or maybe already is been committed. This is not controllable from inside the managed bean. If the response is already been committed, you would not be able anymore to change (redirect) it. Authentication and changing the request/response really needs to be done far before the response is about to be sent.

If you were not homegrowing authentication, then you could have used the Java EE provided container managed authentication for this which is to be declared by <security-constraint> entries in web.xml. Note that this is also decoupled from JSF, but it at least saves you from homegrowing a servlet filter and a managed bean.

The general approach is to group the restricted pages behind a certain URL pattern like /app/*, /private/*, /secured/*, etc and to take the advantage of the fact that JSF stores session scoped beans as HttpSession attributes. Imagine that you've a JSF session scoped managed bean UserManager which holds the logged-in user, then you could check for it as follows:

@WebFilter(urlPatterns={"/app/*"})
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        UserManager userManager = (session != null) ? (UserManager) session.getAttribute("userManager") : null;

        if (userManager == null || !userManager.isLoggedIn()) {
            response.sendRedirect(request.getContextPath() + "/login.xhtml"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    // ...
}

If you're using JSF 2.2+, there's another way to control the response right before it is been sent. You can make use of the <f:viewAction>. Put the following somewhere in your view:

<f:metadata>
    <f:viewAction action="#{authenticator.check}" />
</f:metadata>

with

@Named
@RequestScoped // Scope doesn't matter actually. The listener will always be called on every request.
public class Authenticator {

    public String check() {
        if (authenticated) {
            return null;
        }
        else {
            return "login?faces-redirect=true";
        }
    }

    // ...
}

This is guaranteed to be fired before the response is to be rendered. Otherwise when you do the job in e.g. @PostConstruct, then you may risk java.lang.IllegalStateException: response already committed when the bean is created for the first time when the response has already partially been rendered (and committed).

I only wouldn't consider it to be a "best" practice when it comes to handling HTTP authentication. It makes it too tight coupled into JSF. You should really keep using a servlet filter. But for other purposes, it may be fine.

See also:

Dolores answered 3/9, 2011 at 17:32 Comment(6)
I don't actually want to do a user check, only said that as an example. It's more about prechecking some condition that I will anyway have to handcraft. But then we will go the filter way. ThanksSpicer
Technically, you can. Functionally, this makes no sense. Also, they won't refer the same instance.Dolores
Okay but if my managed bean (ApplicationScope) holds the required information how can the filter evaluate that information? It seems a typical uscase, but quite impossible to do.Spicer
JSF application scoped beans are stored as ServletContext attribute. Make sure that you add eager=true to @ManagedBean to get it to be constructed on webapp's startup.Dolores
The second part of the answer is perfect. Small side question: What's wrong with using faces-config.xml, you sort of mensioned that, that belongs to version 1.x. I think it's very usfull for defining the web flow. How else would this be done? Thanky so much.Spicer
JSF2 supports implicit navigation. If you use action="nextpage", outcome="nextpage", and/or return "nextpage";, it will implicitly go to nextpage.xhtml without the need for a navigation case (which only clutters faces-config.xml if you have many of them). Plus, I personally loathe navigation on POST requests. I normally return void. Better for UX and SEO.Dolores

© 2022 - 2024 — McMap. All rights reserved.