Ignore username in SpringSecurity

Does SpringSecurity have a built-in ability to ignore letter case of a username? For example, if the username is "student001", then it will accept "Student001" as well as "stUdent001".

The reason I need this is because our system uses emails as usernames. Of course, I could do this by extending the DAOAuthenticationProvider class, but I'm just wondering if there is any built-in option for this problem?

+5
source share
3 answers

If you are using DaoAuthenticationProvider, then I assume that you are using it JdbcDaoImpl, which loads users from the JDBC database.

If so, you can override the SQL query that you JdbcDaoImpluse to search for users by manually creating a bean yourself. The default query used by Spring Security:

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

You can use the bottom SQL function to ignore the case:

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

Corresponding Spring XML security configuration:

<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>
+6
source

I believe that any authentication provider uses the UserDetails and UserDetailsService interfaces.

When is the implementation

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

is set for a specialized application UserDetailsService, we can ignore the case usernameand provide UserDetailsfor spring-security to continue further authentication / authorization.

, spring , org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl UserDetailsService user "where username=?". .

+3

gutch is partially correct. It allows a user with JdbcDaoImpl to be case sensitive. But you will also need that the authorization table query also needs to be changed.

<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>
+1
source

All Articles