4

I have implemented my own UserDetailsService. I am configuring spring security in java. How I can create default authentication provider with my custom user service details service and some password encoder?

Thanks in advance Best Regards EDIT: This is what I tried: Here is part of my user details service impl:

public class UserDetailsServiceImpl implements UserDetailsService 

Later in my security config I have something like this:

@Bean
public UserDetailsServiceImpl userDetailsService(){
    return new UserDetailsServiceImpl();
}


@Bean
public AuthenticationManager authenticationManager() throws Exception{
    return auth.build();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder);

However when I run this code I have exception :

Caused by: java.lang.IllegalArgumentException: Can not set com.xxx.UserDetailsServiceImpl field com.....MyAuthenticationProvider.service to com.sun.proxy.$Proxy59
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:741)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:504)
    ... 58 more

I guess I am doing something wrong

John
  • 1,320
  • 4
  • 26
  • 48

1 Answers1

15

Wrong, you should implement your service as follows:

@Service("authService")
public class AuthService implements UserDetailsService {

After that use it in your config:

@Resource(name="authService")
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    ShaPasswordEncoder encoder = new ShaPasswordEncoder();
    auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}

You should NEVER instantiate the beans using new keyword.

astrohome
  • 465
  • 5
  • 16
  • 1
    Thank you for this answer. I've been looking everywhere to figure out why it is `null`. It's deceptive though because in Java config examples, you can routinely see `@Bean` annotated methods returned new'ed up beans. – Vivin Paliath Aug 03 '14 at 22:12
  • 1
    I'm not sure the rule "NEVER instantiate the beans using **new** keyword" is entirely true. Apparently there is some Spring magic going on whith `@Bean` annotated methods in `@Configuration` annotated classes. See http://stackoverflow.com/questions/27990060/calling-a-bean-annotated-method-in-spring-java-configuration – Aner Feb 11 '16 at 20:45