我想使用bcrypt密码编码器,据我所知,它会自动散列并加密密码。
我的代码看起来像这个atm:
@Configuration
@EnableWebSecurity
public class BasicAuthConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
@Autowired
private ConfigService configService;
// Authentication : User --> Roles
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
.withUser(configService.getUsers().getUsername())
.password(configService.getUsers().getPassword())
.roles("USER");
}
// Authorization : Role -> Access
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and().authorizeRequests()
.antMatchers("/actuator/**")
.permitAll()
.antMatchers("/tokenservice/**")
.hasRole("USER")
.antMatchers("/")
.permitAll()
.and().csrf()
.disable()
.headers()
.frameOptions()
.and().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
它的工作方式如下,没有编码{noop}。但是当我这样做时,我得到以下错误:(一行sry,向右滚动)
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext:99 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NullPointerException
从xml文件中读取configService.getConfigurations.getUsername和密码
**编辑 好的,所以我已经验证了2个用户存在,我认为问题在于我试图调用它们的方式。它们存在于配置列表中。 configurations.getUsers()返回两个用户。那么我如何在.withUser()中调用任何用户?
类似configService.getConfigurations()//返回配置.getUsers()//返回用户列表.getsomething ??
答案 0 :(得分:3)
您只需要进行以下更改;
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser(configService.getConfigurations().getUsername1())
.password(configService.getConfigurations().getPassword1())
.roles("USER");
}
将XML文件中的密码设置为散列值。您可以使用下面的小代码片段来获取哈希值。
System.out.println(new BCryptPasswordEncoder().encode("yourpassword"));
另一件事是你可以尝试SCryptPasswordEncoder我曾经为Spring Security项目做过贡献,这更加安全。