JSF是否支持基于表单的安全性

Bas*_*sit 2 jsf-2

我遵循本教程的 安全性在本教程中,我们提到为基于表单的安全性添加类似这样的东西

<form action="j_security_check" method=post>
    <p>username: <input type="text" name="j_username"></p>
    <p>password: <input type="password" name="j_password"></p>
    <p><input type="submit" value="submit"></p>
</form>
Run Code Online (Sandbox Code Playgroud)

但是在JSF形式中,我在h:form中没有动作attributr,我设置为j_security_check.还需要在JSF中使用j_username和j_password来提供基于表单的安全性吗?

谢谢

Bal*_*usC 6

是的,此操作URL和字段名称对于基于表单的身份验证是必需的.这在servlet规范中指定.您可以在JSF页面中按原样使用它.唯一的区别是表单提交和身份验证完全由容器处理,而不是由JSF处理.你不必担心这个.

如果你想要但是在形式更加细粒度的控制过程中提交,或者想利用JSF内置的验证与阿贾克斯的权力等等,那么你可以随时接管它通过编程认证在JSF托管bean.为此,您必须HttpServletRequest#login()在action方法中使用.身份验证仍由容器处理.

例如

<h:form>
    <h:inputText value="#{login.username}" required="true" />
    <h:inputSecret value="#{login.password}" required="true" />
    <h:commandButton value="login" action="#{login.submit}">
        <f:ajax execute="@form" render="@form" />
    </h:commandButton>
    <h:messages />
</h:form>
Run Code Online (Sandbox Code Playgroud)

public String submit() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

    try {
        request.login(username, password);
        return "home?faces-redirect-true";
    } catch (ServletException e) {
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown login", null));
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)