RequestFilter and SessionBean for authorisation

705 Views Asked by At

I am using jsf 2.0 on websphere application server 8.

I have a request filter which authorizes an user. The user authenticates himself against an WebSEAL. The userrole is saved in a MySQL DB. My Requestfilter gets the user principal from the httpServletRequest on each request. Then I look which role the user has (in the DB).

That is very poor, because I have a DB query on each request.

To improve that, I want to implement a SessionBean which contains the username and role. My problem is, that I cant get the sessionbean from my requestfilter. I've tryed to use the sessionbean as managesproperty in the filterclass.

But I always get a Nullpointerexception because the sessionbean is never called before.

So how can I do this? Is this a wrong way?

2

There are 2 best solutions below

0
On BEST ANSWER

JSF stores @SessionScoped @ManagedBeans as an attribute of the HttpSession. So, inside the Filter they are available as follows:

HttpSession session = ((HttpServletRequest) request).getSession();
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean");

You however need to take into account that this approach won't auto-create the bean when it doesn't exist in the scope yet. This will be the case when the filter is invoked for the first time on a fresh new HTTP session. The Filtler is namely invoked before the FacesServlet. You'd then need to create the session bean yourself.

HttpSession session = ((HttpServletRequest) request).getSession();
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean");

if (sessionBean == null) {
    sessionBean = new SessionBean();
    session.setAttribute("sessionBean", sessionBean);
}

// ...

sessionBean.setRole(role);

// ...

JSF won't override it with a new instance whenever it already exist in the session scope, but just reuse the very same instance as created in the Filter.

In case you're already using CDI @Named to manage beans instead of the in JSF 2.3 deprecated and Faces 4.0 removed @ManagedBean, then simply @Inject it in the Filter.

See also:

4
On

See my similar answer, you should be able to obtain your SessionBean this way

EDIT

Or you can try this approach

 HttpSession session = (req (HttpServletRequest)).getSession();
 MyManagedBean myManagedBean = session.getAttribute("myManagedBean");`

Or you could use PhaseListener instead of your filter. See this nice article about using PhaseListener for securing your app.