我在使用内存中设置用户的简单登录配置时遇到问题。所有的时间我都回到不良凭证。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.userDetailsService(userDetailsService);
auth.
inMemoryAuthentication()
.withUser("user").password("123").roles("USER")
.and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/location")
.hasAnyRole("ADMIN","USER")
.and()
.formLogin()
.and()
.csrf()
.disable();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
我做错了什么?
答案 0 :(得分:1)
此答案随附完整的working sample和unit tests。
让我们简化一些事情。如果您使用的是formLogin()
,则只需指定一个UserDetailsBean
,然后即可将其与编码器一起使用:
@Bean
public PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
builder()
.passwordEncoder(input -> passwordEncoder().encode(input))
.username("user")
.password("123")
.roles("USER")
.build(),
builder()
.passwordEncoder(input -> passwordEncoder().encode(input))
.username("admin")
.password("password")
.roles("USER", "ADMIN")
.build()
);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
//application security
.authorizeRequests()
.mvcMatchers("/non-secure/**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
;
// @formatter:on
}
非常欢迎您下载示例并在IDE中运行unit tests
现在,这不是不是的首选方式,因为您的代码中包含明文密码。您可以将其替换为已经拥有passwords encrypted的经理。
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
builder()
.username("user")
.password("{bcrypt}$2a$10$C8c78G3SRJpy268vInPUFu.3lcNHG9SaNAPdSaIOy.1TJIio0cmTK")
.roles("USER")
.build(),
builder()
.username("admin")
.password("{bcrypt}$2a$10$XvWhl0acx2D2hvpOPd/rPuPA48nQGxOFom1NqhxNN9ST1p9lla3bG")
.roles("USER", "ADMIN")
.build()
);
}