如何从 JSF 表单中进行 Spring Security 身份验证

2024-05-01

我创建了一个简单的 JSF 登录页面,并尝试将其与 spring security 集成。

这是来自的表单元素登录.xhtml

    <h:form>

     <h:outputLabel value="User Id:" for="userId"/>

     <h:inputText id="j_username" label="User Id"
     required="true"   value="#{loginBean.name}" >

     </h:inputText>

     <h:outputLabel value="Password: "  for ="password"/>

     <h:inputSecret id="j_password" value="#{loginBean.password}" />

     <h:commandButton value="Submit" action="#{j_spring_security_check}" />

 </h:form>

但是渲染的 html 页面有类似下面的内容。查看表单操作和输入标签的名称

表单元素


Spring Security 有两种工作方式。

Use prependId="false"在 JSF 表单上

As <h:form>是一个命名容器,它在其子级的 id 前面加上指定的id,或自动生成的 id,因此 Spring Security 期望 id 保持不受链接状态,只是不要在前面添加 id:

 <h:form prependId="false">
     <h:outputLabel value="User Id: " for="userId" />
     <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" />
     <h:outputLabel value="Password: "  for ="password" />
     <h:inputSecret id="j_password" value="#{loginBean.password}" />
     <h:commandButton value="Submit" action="#{loginBean.login}" />
</h:form>

注意#{j_spring_security_check}是错误的操作方法:需要#{loginBean.login}包含以下内容:

public String login() {
    //do any job with the associated values that you've got from the user, like persisting attempted login, etc.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext extenalContext = facesContext.getExternalContext();
    RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check");
    dispatcher.forward((ServletRequest)extenalContext.getRequest(), (ServletResponse)extenalContext.getResponse());
    facesContext.responseComplete();
    return null;
}

基本上,您需要做的就是发送到/j_spring_security_check并有j_username and j_password作为请求参数。

使用纯 HTML 表单

基本上,在这个问题上没有特别需要搞乱 JSF 表单,以防除了身份验证之外不需要做一些额外的事情,并且纯 HTML 表单足以让 Spring Security 完成其工作。

<form action="/j_spring_security_check" method="POST">
    <label for="j_username">User Id: </label>
    <input id="j_username" name="j_username" type="text" />
    <label for="j_password">Password: </label>
    <input id="j_password" name="j_password" type="password"/>
    <input type="submit" value="Submit"/>
</form>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 JSF 表单中进行 Spring Security 身份验证 的相关文章

随机推荐