0
votes

I have situation like this.

I'm using Spring boot 1.3.2, and I have installed MongoDB on my pc I have added dependency

org.springframework.boot:spring-boot-starter-data-mongodb

And when I run my web application, database connection automatically start working.

I didn't configure a thing.

Now I want to connect spring security like this:

@Override
protected void configure(AuthenticationManagerBuilder auth)
                                                   throws Exception {
  auth
    .jdbcAuthentication()
      .dataSource(dataSource);
}

My question is what is default bean name for Spring Boot DataSource and can I override it?

1

1 Answers

3
votes

If you're planning to use Mongodb as your user details storage, i.e. username, password, etc. , then you can't use the jdbcAuthentication(). Instead, You could use a UserDetailsService in order to achieve the same:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired private MongoTemplate template;

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService((String username) -> {
                    User user = template.findOne(Query.query(Criteria.where("username").is(username)), User.class, "users");

                    if (user == null) throw new UsernameNotFoundException("Invalid User");

                    return new UserDetails(...);
                });
    }
}

In the prceeding sample, i supposed that you have a users collection with a username field. If exactly one user exists for the given username, you should return an implementation of UserDetails corresponding to that user. Otherwise, you should throw a UsernameNotFoundException.

You also have other options for handling user authentication but jdbcAuthentication() is off the table, since you're using a NoSQL datastore for storing user details and JDBC is an abstraction for handling all the talkings with Relational databases.