2012-06-07 147 views
5

确实SpringSecurity有一些内置的忽略用户名的字母大小写的能力吗?例如,如果用户名是“student001”,那么它将接受“Student001”以及“stUdent001”。忽略SpringSecurity用户名的情况下

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

回答

6

如果您使用的是DaoAuthenticationProvider,那么我认为您使用的是JdbcDaoImpl,它会从JDBC数据库加载用户。

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

select username,password,enabled from users where username = ? 

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

select username,password,enabled from users where lower(username) = lower(?) 

适当的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> 
+0

在[http://static.springsource.org/spring-security/site/docs/3.1.x/reference/appendix-schema.html],用户名柱用**忽略大小写创建** :'username varchar_ignorecase(50)not null primary key' – BenC

+0

该页面记录了HSQLDB的SQL语句。其他数据库可能支持或不支持'varchar_ignorecase' ...例如我使用不支持它的PostgreSQL。 PostgreSQL确实有一个附加的'citext'模块,它做了类似的事情,但是它在旧版本中并没有默认安装,因此向查询添加'lower()'是一个更简单的解决方案。 – gutch

3

相信的UserDetails和UserDetailsS​​ervice的接口的任何身份验证提供者有机可乘。

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

的实现自定义应用程序特定UserDetailsService给出,我们可以忽略的username的情况,并提供UserDetails弹簧,安全性进一步的验证/授权进行。

但是,如果弹簧提供org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl用作 UserDetailsService它将与条件"where username=?"user表加载的UserDetails。所以它是区分大小写的。

1

gutch部分是正确的。它允许用户使用JdbcDaoImpl对用户表进行不区分大小写的检查。但是你将需要权威表查询也需要改变。

<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(?)" /> 
    <property name="authoritiesByUsernameQuery" value="select username,authority " + 
     "from authorities where lower(username) = lower(?)" /> 
</bean>