2012-06-07 71 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>