繁体   English   中英

如何在Spring中使用注释定义PasswordEncoder?

[英]How do I define a PasswordEncoder using annotations in Spring?

我正在使用Spring-Boot v1.3.0.M2。 我正在尝试使用注释定义osscpPasswordEncoder 我的配置类如下所示。 这个例子很好用。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 @Bean
 public PasswordEncoder getPasswordEncoder() { 
  return new StandardPasswordEncoder();
 }
}

但是,我想用一个秘密实例化StandardPasswordEncoder ,并且我对类进行了如下修改。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 @Autowired
 @Value(value="${password.secret}")
 private String secret;

 @Bean
 public PasswordEncoder getPasswordEncoder() { 
  return new StandardPasswordEncoder(secret);
 }
}

请注意,我的Spring-Boot应用程序如下所示。

@SpringBootApplication
@PropertySource("classpath:/config/myapp.properties")
public class Application {
 public static void main(String[] args) {
  SpringApplications.run(Application.class, args);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholdConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}

我的myapp.properties如下所示。

password.secret=fsdkjfsldfsdfsdfsdf

当我尝试运行Spring-Boot应用程序时,出现以下异常。


Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.crypto.password.PasswordEncoder]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getPasswordEncoder' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 102 more

因为字段private String secret;所以无法实例化PasswordEncoder private String secret; 未设置,因此NullPointerException (NPE)。 我试图使方法getPasswordEncoder以及字段secret静态的,但这无济于事。

关于如何使用注释来秘密获取PasswordEncoder实例的任何想法?

Spring推荐在SHA或MD5上使用的bcrypt密码加密器可以这样配置:

@Bean
public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
}

我通过修补找到了答案。 我删除了字段secret ,仅使用方法对参数进行了注释,如下所示。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 @Bean
 public PasswordEncoder getPasswordEncoder(@Value(value="${password.secret}") String secret) { 
  return new StandardPasswordEncoder(secret);
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM