自定义 UserDetailsS​​ervice 中 loadUserByUsername 的参数 username 始终为空

IT小君   2022-09-15T08:08:14

我正在使用带有自定义 UserDetailsS​​ervice 的 spring-security 进行基于表单的登录。登录表单似乎已正确提交。在调试应用程序时,我发现提交的请求到达了 UsernamePasswordAuthenticationFilter 的尝试身份验证方法。但看起来请求参数无法映射到用户名和密码字段,因为它们仍然为空。因此,我的自定义 UserDetailsS​​ervice 的 loadByUsername 方法的参数用户名仍然为空,我无法成功登录。

我已经尝试了很多,但现在我不知道问题可能是什么。我对 spring-security 也很陌生,但我想我离得太远了。

我尽可能地总结了代码。如果您需要更多信息,请现在告诉我。

首先我在 web.xml 中设置了 springSecurityFilterChain:

<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:WEB-INF/applicationContext.xml,
        classpath:WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
</context-param>

<!-- Filter Config -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<!-- Filter Mappings -->
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

<!-- Spring Configuration -->
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>

那是我的 applicationContext.xml 与 customUserDetailsS​​ervice 的引用:

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    ...
</bean>

<bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    ...
</bean>

<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    ...
</bean>

<!-- Authentification -->
<bean id="customUserDetailsService" class="com.seraphim.security.auth.CustomUserDetailsService"/>

<!-- Transaction -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>

<context:component-scan base-package="com.seraphim"/>

<context:annotation-config/>

<tx:annotation-driven transaction-manager="transactionManager"/>

具有适当身份验证提供程序的 applicationContext-security.xml:

<http
    auto-config="true"
    access-denied-page="/accessDenied.jsp">

    <intercept-url
            pattern="/pages/**"
            access="ROLE_ADMIN,ROLE_USER"/>
    <intercept-url
            pattern="/**"
            access="IS_AUTHENTICATED_ANONYMOUSLY"/>

    <form-login
            login-processing-url="/j_spring_security_check"
            login-page="/index.xhtml"
            default-target-url="/pages/main.xhtml"
            authentication-failure-url="/index.xhtml"/>

    <logout
            logout-url="/logout*"
            logout-success-url="/"/>

</http>

<authentication-manager>
    <authentication-provider user-service-ref="customUserDetailsService">
        <password-encoder hash="md5"/>
    </authentication-provider>
</authentication-manager>

在 faces-config.xml 我添加了一个 LoginErrorPhaseListener 来检测 BadCredentialsException 并添加了 LoginBean:

<lifecycle>
    <phase-listener>com.seraphim.security.auth.LoginErrorPhaseListener</phase-listener>
</lifecycle>

<managed-bean>
    <managed-bean-name>loginBean</managed-bean-name>
    <managed-bean-class>
        com.seraphim.bean.LoginBean
    </managed-bean-class>
    <managed-bean-scope>
        request
    </managed-bean-scope>
</managed-bean>

index.xhtml 包含用户名和密码字段,并提交给 loginBean:

<h:form id="loginForm">

    <h:outputLabel for="j_username" value="User:"/>
    <p:inputText id='j_username' label="user" required="true"/>

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

    <h:inputSecret id='j_password' label="pass2" required="true"/>

    <h:outputLabel for="_spring_security_remember_me" value="Remember "/>
    <p:selectBooleanCheckbox id='_spring_security_remember_me'/>

    <h:outputLabel/>
    <h:commandButton type="submit" id="login" action="#{loginBean.doLogin}" value="Login"/>

</h:form>

登录Bean.java

@Component
@Scope("request")
public class LoginBean {

  public String doLogin() throws IOException, ServletException {

    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

    RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
            .getRequestDispatcher("/j_spring_security_check");

    dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());

    FacesContext.getCurrentInstance().responseComplete();

    // It's OK to return null here because Faces is just going to exit.
    return null;

  }
}

现在在 CustomUserDetailsS​​ervice.java 中应该加载正确的用户,但这里的方法参数 username 始终为空(不是 null)。因此当然找不到有效用户:

public class CustomUserDetailsService implements UserDetailsService {

@Resource
IUserDao userDao;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userDao.findByUsername(username);

    if (user == null) {
        throw new UsernameNotFoundException("user not found");
    }

    // build roles for user
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    if(user.isAdmin()) {
        authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
    }

    return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            user.isEnabled(), 
            user.isAccountNonExpired(),
            user.isCredentialsNonExpired(), 
            user.isAccountNonLocked(),
            authorities);
}

}

希望你能帮助我解决这个问题。

点击广告,支持我们为你提供更好的服务
评论(1)
IT小君

如果您以这种方式将 Spring Security 与 JSF 集成,则需要prependId = "false"在表单中进行设置,否则 Spring Security 所需的字段名称将带有表单 ID:

<h:form id="loginForm" prependId = "false">...</h:form>
2022-09-15T08:08:14   回复