Friday 11 July 2008

Oracle ADF: My simple UserInfo bean class

Some time ago, I posted a link to the JDeveloper forum regarding how to use he isUserInRole() method of the ExternalContext class in order to determine whether or not the current application user is assigned a role.

Since I have lost the original post, I am giving to display sample code showing how to reference the function, how to declare the bean in faces-config.xml and also how to use it.

Let's suppose that you our application has two roles. User and admin. Definitions ofr these roles is included in jazn-data.xml.

package mycompany.myapplication.view.beans;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

public class UserInfo {
   
    private boolean admin;
    private boolean user;

    public UserInfo()
    {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        
        user = ec.isUserInRole("user");
        admin = ec.isUserInRole("admin");
    }
    
    public boolean isUser()
    {
        return user;
    }
    
    public boolean isAdmin()
    {
        return admin;
    }
}

The next step is to define the bean in faces-config.xml

  <managed-bean>
    <managed-bean-name>UserInfo</managed-bean-name>
    <managed-bean-class>mycompany.myapplication.view.beans.UserInfo</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

Finally enabling or disabling a menu item property based on whether the user is an admin, is done like this

             <af:commandMenuItem text="#{res['menutabs.AdminAction']}"
                                    action="adminAction"
                                    disabled="#{!UserInfo.admin}"/>

By the same token preventing a page from being display is done like this

          <af:panelPage title="#{res['pages.pricelist.BasicFees.title']}"
                        rendered="#{UserInfo.admin}">

The truth of the matter is that I ended up using all that because I could not succeed in making j2ee security work for my application. Despite Chris Muir's hints on the JDeveloper forum, there was no way I could deny access to certain parts of my application, so I ended up enforcing security using my simple UserInfo bean that I hooked into the disabled and rendered properties of menu and panelPage tags of the protected pages like I showed before.

That way if anyone runs the application by going from the standard path, then he won't be able to access the admin pages and if he calls the pages directly, then he will see nothing.

No comments :