Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring's "user-by-username-query" clause in a Java class?

I am using Spring security to validate user login.
User credentials are stored in database.
Here is the related section from my "appContext-security.xml" file.

This code works - but my problem is that I am using raw SQL query for "user-by-username-query" and "authorities-by-username-query' tags. Thus if I have to support multiple databases and if the Sql syntax varies, then I have a problem.

So can I put those queries in some form of a Java class? so that I can change the SQL syntax in that java class easily and make these SQLs DB dependent?

<authentication-manager alias="authManager">
        <authentication-provider>
            <password-encoder hash="md5"/>
            <jdbc-user-service data-source-ref="jndiDataSource"
                users-by-username-query="select name, password, enabled from USER where user_status&lt;&gt;0 and name=?"
                authorities-by-username-query="select m.name,p.name from USER m, ROLE p where m.name=? and m.application_role=p.id"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <beans:property name="jndiName" value="java:/appManaged"/>
    </beans:bean>

Any help will be much appreciated.

like image 982
javauser71 Avatar asked Aug 04 '11 17:08

javauser71


1 Answers

You can declare JdbcDaoImpl as a bean manually instead of using <jdbc-user-service>:

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

<beans:bean id = "jdbcUserService" 
    class = "org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
    <beans:property name = "dataSource" ref = "jndiDataSource" />
    <beans:property name = "usersByUsernameQuery" 
         value = "select name, password, enabled from USER where user_status&lt;&gt;0 and name=?"
" />
    ...
</beans:bean>

Then you can do whatever you want, for example, declare it to be obtained from a factory that sets appropriate queries, or something like that.

like image 171
axtavt Avatar answered Sep 27 '22 17:09

axtavt