This post shows how to restrict page access based on Role using pages.xml in JBoss Seam.
addquestion.xhtml is the UI to enable user to add questions [say in an exam]. If we are to allow only users having role as admin to access the page, we make the following entry in the pages.xml.
<page view-id="/addquestion.xhtml" login-required="true">
<restrict>#{s:hasRole('admin')}</restrict>
</page>
The role is set in the backing bean which authenticates and logs in the user as below. Here we have two roles admin and student. Only admin users are allowed to access the add question page. Admin and Student are the related JPA entity classes which maps to the related tables where admin credentials and student credentials are stored.
import com.ts.entity.Admin;
import com.ts.entity.Student;
import static org.jboss.seam.ScopeType.SESSION;
import java.util.List;
import javax.persistence.EntityManager;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.security.Identity;
@Name("authenticator")
public class AuthenticatorAction {
@In
EntityManager em;
@Out(required = false, scope = SESSION)
private Admin admin;
@Out(required = false, scope = SESSION)
private Student student;
@In
private Identity identity;
public boolean authenticate() {
List results = em.createQuery("select u from Admin u where u.username=#{identity.username} and u.password=#{identity.password}").getResultList();
if (results.size() != 0) {
admin = (Admin) results.get(0);
identity.addRole("admin");
return true;
}
results = em.createQuery("select u from Student u where u.username=#{identity.username} and u.password=#{identity.password}").getResultList();
if (results.size() != 0) {
student = (Student) results.get(0);
identity.addRole("student");
return true;
}
return false;
}
}
Important:
We must specify an exception in pages.xml as below. Else the AuthorizationException will be swallowed [though we can see the Exception on the log files and in server console] and the user will be allowed to access the page. That is without the below exception entry an user with role as student will be allowed to access add question page.
<exception class="org.jboss.seam.security.AuthorizationException">
<redirect view-id="/main.xhtml">
<message>You don't have permission to do this</message>
</redirect>
</exception>
