Spring Boot, Spring security linked with database Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Spring Boot, Spring security linked with database without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Sorry in advance for my bad english..

I am a beginner with Spring. A colleague advised me to use Spring boot to begin. For the moment I like that.

To begin I want to create an authentication / login module linked with a mySQL database.

I am working on IntelliJ and phpMyAdmin.

For this job there are 3 parts:
– Authentication system – OK
– Database link and basic operations – OK
– Link between authentication and database – NOT OK.



For the moment, for the authentication I have this file :

WebSecurityConfig.java

package hello;

//imports


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER");
}
}



To connect my aplication with the database I have this file :

application.properties

spring.datasource.url = jdbc:mysql://localhost/simulateur
spring.datasource.username =  root
spring.datasource.password =

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

I like this solution because it is remember me solution with Play Framework and a solution at my entreprise. I wish keep this file : application.properties. One config file seems me great.



To link all that, I found a solution on this website. I have to add this in my WebSecurityConfig.java :

@Autowired
DataSource dataSource;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

  auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
 "select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery(
 "select username, role from user_roles where username=?");
 } 


And add this in file MvcConfig.java with routes and other features with correct parameters:

@Bean(name = "dataSource")
 public DriverManagerDataSource dataSource() {
 DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
 driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
 driverManagerDataSource.setUrl("jdbc:mysql://localhost/simulateur");
 driverManagerDataSource.setUsername("root");
 driverManagerDataSource.setPassword("");
 return driverManagerDataSource;
 }



My problem is that I have the impression to redefine database connection. I would like to use my file : application.properties. Have you an idea to use this file and don’t use the part of code in MvcConfig.java ?



Thank you in advance for your help ! 🙂

Answer

In spring boot you have two ways of defining a datasource, either you define it on the application.properties, or you do it programmatically. Unless you require some very specific configuration, or you have more than one datasource, you should define your datasource configuration on your application.properties so springboot will autoconfigure everything for you.

In the example you provided you are defining the datasource twice, you should remove the MvcConfig.java.

I recommend that you read this article about how to work with sql databases and spring boot Working with SQL databases

We are here to answer your question about Spring Boot, Spring security linked with database - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji