【问题标题】:Spring security authentication provider java configSpring安全认证提供者java配置
【发布时间】:2014-04-08 00:45:20
【问题描述】:

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

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

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

我想我做错了什么

【问题讨论】:

  • 嗨,约翰,到目前为止,您尝试了什么?你是否已经实现了AuthenticationProvider

标签: spring spring-security


【解决方案1】:

错了,你应该如下实现你的服务:

@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。

【讨论】:

  • 感谢您的回答。我一直在到处寻找为什么它是null。虽然它具有欺骗性,因为在 Java 配置示例中,您通常可以看到 @Bean 带注释的方法返回新的 bean。
  • 我不确定“永远不要使用 new 关键字实例化 bean”规则是否完全正确。显然,@Bean @Configuration 带注释的类中的带注释方法正在发生一些 Spring 魔术。见stackoverflow.com/questions/27990060/…
猜你喜欢
  • 1970-01-01
  • 2016-06-25
  • 2016-04-22
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
相关资源
最近更新 更多