Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot with custom UserDetailsService

Tags:

What is the correct way to add my custom implementation of UserDetailsService (which uses Spring Data JPA) to Spring Boot app?

public class DatabaseUserDetailsService implements UserDetailsService {

    @Inject
    private UserAccountService userAccountService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userAccountService.getUserByEmail(username);
        return new MyUserDetails(user);
    }

}


public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {

    public User findByEmail(String email);

}



@Service
public class UserAccountService {

    @Inject
    protected UserRepository userRepository;

    public User getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

}


@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.sample")
@EntityScan(basePackages = { "com.sample" })
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    ...

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

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


    }

    @Order(Ordered.HIGHEST_PRECEDENCE + 10)
    protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {

        @Inject
        private UserAccountService userAccountService;

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService());
        }

        @Bean
        public UserDetailsService userDetailsService() {
            return new DatabaseUserDetailsService();
        }

    }

}


@Entity
public class User extends AbstractPersistable<Long> {

    @ManyToMany
    private List<Role> roles = new ArrayList<Role>();

    // getter, setter

}


@Entity
public class Role extends AbstractPersistable<Long> {

    @Column(nullable = false)
    private String authority;

    // getter, setter

}

I cannot start app beacouse I get (full exception here http://pastebin.com/gM804mvQ)

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.sample.model.User.roles[com.sample.model.Role]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1134)

When I configure my ApplicationSecurity with auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...") everything is working including JPA and Spring Data repositories.

like image 596
igo Avatar asked Jul 13 '14 13:07

igo


People also ask

What is spring boot UserDetailsService?

UserDetailsService is used by DaoAuthenticationProvider for retrieving a username, password, and other attributes for authenticating with a username and password. Spring Security provides in-memory and JDBC implementations of UserDetailsService .

How do I override UserDetailsService?

If you override UserDetailsSeervice and verify the username and password by override loadUserByUsername(), in your case it is static values(I would recommend for static users use inMemoryAuthentication). this will tell your authenticationManager to use userDetailsService which is been implemented for authentication.

Which method in UserDetailsService needs to be implemented so that Spring Security Framework can get the user details of a specific user?

The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which can be overridden to customize the process of finding the user. It is used by the DaoAuthenticationProvider to load details about the user during authentication.


2 Answers

Your app seems to work for me (once I added @Configuration to the AuthenticationSecurity). Here's another working sample of a simple app with JPA UserDetailsService in case it helps: https://github.com/scratches/jpa-method-security-sample

like image 91
Dave Syer Avatar answered Sep 22 '22 18:09

Dave Syer


You can also follow this blog to implement custom user details service.

This example shows how you can send bean to userdetails service for injection.

  1. Autowire the Repository in the WebSecurityConfigurer
  2. Send this bean as a parameter to the user details service by a parameterized constructor.
  3. assign this a private member and use to load users from database.
like image 43
Ekansh Rastogi Avatar answered Sep 18 '22 18:09

Ekansh Rastogi