Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security authentication provider java config

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

like image 279
John Avatar asked Dec 06 '22 03:12

John


1 Answers

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.

like image 52
astrohome Avatar answered Dec 24 '22 13:12

astrohome