0

我正在关注链接http://docs.oracle.com/cd/E19798-01/821-1841/bncby/index.html来学习基于表单的身份验证。我已经完成了执行基于表单的身份验证所需的操作,但是在签入角色时我总是取假。这是我的配置。我错过了什么?

AutoBean.java

public void login(){
        HttpServletRequest request = getHttpServletRequest();
        boolean intutRole=request.isUserInRole("TutorialUser");
        System.out.println("intutRole:"+intutRole);
        System.out.println(request.getContentLength());
    }

    protected HttpServletRequest getHttpServletRequest(){
        FacesContext fc = getFacesContext();
        ExternalContext ec = fc.getExternalContext();
        HttpServletRequest request = (HttpServletRequest)ec.getRequest();
        return request;
    }

    protected FacesContext getFacesContext(){
        FacesContext fc = FacesContext.getCurrentInstance();
        return fc;
    }

在此处输入图像描述
web.xml

  <!-- Form Based Authentication -->
    <security-constraint>
        <display-name>Constraint1</display-name>
        <web-resource-collection>
            <web-resource-name>wrcoll</web-resource-name>
            <description/>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>TutorialUser</role-name>
        </auth-constraint>
    </security-constraint>


    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>file</realm-name>
        <form-login-config>
            <form-login-page>/login.xhtml</form-login-page>
            <form-error-page>/error.xhtml</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <description/>
        <role-name>TutorialUser</role-name>
    </security-role>
4

1 回答 1

0

添加调用 request.login(username, password) 后,它可以工作。

public void login() {
    HttpServletRequest request = getHttpServletRequest();
    try {
        request.login(username, password);          
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    boolean intutRole = request.isUserInRole("TutorialUser");
    System.out.println("intutRole:" + intutRole);
    System.out.println(request.getContentLength());
}

确保您使用的是 Servlet 3.0。HttpServletRequest 在之前的 Servlet 版本中没有登录方法。所以你必须在 pom.xml 中添加以下依赖项

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>
于 2013-06-21T05:29:26.333 回答