在SpringSecurity中忽略用户名的情况

Hoà*_*ong 6 java spring-mvc spring-security

SpringSecurity是否有一些内置的能力来忽略用户名的字母大小写?例如,如果用户名是"student001",那么它将接受"Student001"以及"stUdent001".

我需要这个的原因是我们的系统使用电子邮件作为用户名.当然我可以通过扩展DAOAuthenticationProvider类来做到这一点,但我只是想知道这个问题是否存在任何内置选项?

gut*_*tch 6

如果你正在使用DaoAuthenticationProvider那么我假设你正在使用JdbcDaoImplwith,它从JDBC数据库加载用户.

如果是这样,您可以JdbcDaoImpl通过自己手动创建bean 来覆盖用于查找用户的SQL查询.Spring Security使用的默认查询是:

select username,password,enabled from users where username = ?
Run Code Online (Sandbox Code Playgroud)

您可以使用SQL lower函数忽略大小写:

select username,password,enabled from users where lower(username) = lower(?)
Run Code Online (Sandbox Code Playgroud)

适当的Spring Security XML配置是:

<bean id="org.springframework.security.authenticationManager" class="org.springframework.security.authentication.ProviderManager">
    <property name="providers">
        <list>
            <ref bean="daoAuthenticationProvider"/>
        </list>
    </property>
</bean>

<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="caseInsensitiveUserDetailsService"/>
</bean>

<bean id="caseInsensitiveUserDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
    <property name="usersByUsernameQuery" value="select username, password, enabled from users where lower(username) = lower(?)" />
</bean>
Run Code Online (Sandbox Code Playgroud)