The JDBC authentication

Spring Security supports using UserDetailsService to read the authentication information from database tables that internally uses Spring-JDBC. To use the JDBC authentication, we will need to configure the bean for UserDetailsService in the configuration file. In the demo, we will discuss the configuration in detail. Irrespective of which database we are using in order to perform the authentication, the following schema must be present in the database:

CREATE TABLE users ( 
   username VARCHAR(50) NOT NULL PRIMARY KEY, 
   password VARCHAR(50) NOT NULL, 
   enabled BIT NOT NULL 
); 

The values from the enabled column will provide the information on whether the account is enabled or disabled:

CREATE TABLE authorities ( 
   username VARCHAR(50) NOT NULL, 
   authority VARCHAR(50) NOT NULL 
); 
ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users foreign key
(username) REFERENCES users(username);

I guess now it's time to practically check how the JDBC authentication will be used.

Let's update Ch08_Security_Getting_Started to add the JDBC-based authentication with the help of the following steps:

  1. As the data will be loaded from the database, we will need to add the JARs for spring-JDBC, spring-tx, mysql-connector as well.
  2. In the spring-security.xml file, we need to change the authentication provider. Delete the configuration for <authentication-manager> or comment it.
  3. The updated configuration that enables the credentials to be checked against the data stored in the database is as follows:
<bean id="userDetailsService" class=     
  "org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> 
    <property name="dataSource" ref="dataSource"/> 
</bean> 
  1. As the authentication is done against the database, the beans to set the database connection need to be configured, whose ID will be dataSource, as shown here:
<bean id="dataSource" class= 
   "org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <!-- other connection properties as we did in Spring-JDBC module-->  
</bean>    
  1. As the data is checked against the database, let's create the users and authorities table by following the DDL that we discussed at the time of the JDBC authentication.
  2. Add the records to both, the users and authorities table, with the same privileges and credentials as we did in Ch08_Security_Getting_Started. The following screenshot displays the sample data that we will use for our application:
  1. We don't have to change anything else as we are not changing the flow of the application.
  2. Execute the application and run it the same way as we did in earlier cases. Don't forget to use the correct username and password with the role specified in the intercept-url attribute.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.125