如何限制未登录用户访问某些页面? (JSF 2.0)

时间:2011-04-14 09:55:54

标签: java jsf java-ee jsf-2 java-ee-6

我正在实施自己的身份验证机制,我想知道我在做什么是正确的,如果不能,我怎么能正确地做到这一点。

首先解释我的身份验证机制是如何工作的:

- 我的用户的详细信息位于名为Role的对象中。该对象包含3个字段:

电子邮件:String

密码:String

的用户类型:Enum

- 当用户访问系统时,对象Role将保存到会话中。

我的问题是:如何根据userType字段限制对用户(角色)访问某些页面?

这就是我的所作所为但不起作用。

首先我有一个托管bean来检查usser是否已被记录。

@ManagedBean
@RequestScoped
public class SecurityController {

    //Some attributes...


    public String redirectNotBuyer() {
        Role role = (Role) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("userRole");
        //Checks if user is logged
        if (role == null) {         
            // Please login
            //Add message to authentification
            return "login.xhtml";           
        } else if (role != null) {
            if (!role.getType().toString().equalsIgnoreCase("BUYER")) {
                // Buyer not authorized
                return "main.xhtml";
            }
        }       
        return null;
    }

    public String redirectNotSeller() {
        Role role = (Role) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("userRole");
        if (role == null) {
            // Please login
            //Add message to authentification
            return "login.xhtml";           
        } else if (role != null) {
            if (!role.getType().toString().equalsIgnoreCase("SELLERs")) {
                // Buyer not authorized
                return "main.xhtml";
            }
        }       
        return null;
    }

//Getters, setters...

如果用户不是买方,并且用户不是卖家,则上述两种方法会重定向。

所以现在我所做的是在我不希望用户去的页面中我调用其中一种方法,因此用户被重定向到主页面。 示例:非授权用户输入名为buyOffer.xhtml的页面,只有买方才能访问:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">


<ui:composition template="WEB-INF/templates/BasicTemplate.xhtml">
    <!-- THE REGISTRATION FORM -->
    <ui:define name="buyOfferForm">
       <h2>Buy offer</h2>
       #{SecurityController.redirectNotBuyer()}
    </ui:define>            
</ui:composition>

</html>

出于某种原因,当我使用未登录的用户或没有BUYER作为userType的用户访问此页面时,它不会被重定向到main.xhtml页面。那是为什么?

1 个答案:

答案 0 :(得分:5)

正确的机制是使用Filter

查看