Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mysql database to authenticate users in Spring security?

I want to use Spring security to authenticate users in my web application.. Since am not a matured user to Spring framework ,i can't get a clear idea about how we can do the configuration settings to use jdbc-user-service .. i had done the following configurations.but its not working

<authentication-manager>
    <authentication-provider>
         <jdbc-user-service data-source-ref="myDataSource"/>
    </authentication-provider>        
</authentication-manager>
<beans:bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url" value="jdbc:mysql://localhost:3306/testDB"/>
    <beans:property name="username" value="admin"/>
    <beans:property name="password" value="admin"/>
</beans:bean>

..can anyone please help me to solve the issue with a sample config file. Thanks in advance.

like image 933
TKV Avatar asked Aug 24 '11 06:08

TKV


2 Answers

another way to do this is to create tables using the standard spring security database schema (http://static.springsource.org/spring-security/site/docs/3.0.x/reference/appendix-schema.html). Then you can simply use spring's jdbc-userservice:

<security:authentication-provider >
    <security:jdbc-user-service data-source-ref="dataSource" /> 
    <security:password-encoder hash="sha" />
</security:authentication-provider>

Or if you want to use your own schema you can override the queries like this:

<security:authentication-provider>
    <securiy:jdbc-user-service 
      data-source-ref="dataSource"
      users-by-username-query="select username, password from users where username=?"
      authorities-by-username-query="select username, roleName from role..."
      role-prefix="ROLE_"
    />
 </security:authentication-provider>
like image 90
Jens Avatar answered Sep 18 '22 04:09

Jens


You usually do it with a custom UserDetailsService. The UserDetailsService is a DAO used to load data about a user when they attempt login. Have a look at the loadUserByUsername(String username) method and the UserDetails class in spring.

Yo need to define it in your context:

<bean id="myDetailsService"
    class="com.company.service.impl.MyDetailsService" />

To use it you can add this to your security config:

<authentication-manager>
    <authentication-provider user-service-ref="myDetailsService" />
</authentication-manager>

and all you security filters will use it.

You can ask a more specific question if you need help implementing it, but you won't have trouble IMO.

like image 28
Simeon Avatar answered Sep 19 '22 04:09

Simeon