Spring安全认证提供程序java配置

时间:2014-03-05 18:48:55

标签: spring spring-security

我已经实现了自己的UserDetailsS​​ervice。我在java中配置spring security。如何使用我的自定义用户服务详细信息服务和一些密码编码器创建默认身份验证提供程序?

提前致谢 最好的祝福 编辑: 这是我试过的: 以下是我的用户详细信息服务的一部分:

public class UserDetailsServiceImpl implements UserDetailsService 

稍后在我的安全配置中我有这样的事情:

@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);

但是,当我运行此代码时,我有异常:

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

我想我做错了什么

1 个答案:

答案 0 :(得分:15)

错误,您应按如下方式实施服务:

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

之后在配置中使用它:

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

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

您绝不应使用 new 关键字来实例化bean。