我有一个 Spring Boot 应用程序,我想用不同的凭据保护不同的端点。 我认为角色是实现这一点的最佳(唯一?)方式,并已写道:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String ROLE_1 = "role1";
private static final String ROLE_2 = "role2";
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles(ROLE_1)
.and()
.withUser("user2").password("user2Pass").roles(ROLE_2);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/endpoint1").hasRole(ROLE_1)
.antMatchers("/endpoint2").hasRole(ROLE_2)
.antMatchers("/").permitAll().and().httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.headers().frameOptions().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
但是当我调用任一端点(使用来自 configure
的凭据)时,我得到 401 Unauthorized
。为什么我在 configure
中指定的凭据不被接受?
答案 0 :(得分:0)
因为你告诉 spring 生成的哈希是密码。而不是你的密码,所以它会被双重散列。
.password(passwordEncoder().encode("user1Pass"))
如果您查看 official documentation,它向您展示了您应该如何构建您的用户,您应该使用 withDefaultPasswordEncoder
并且 spring 将为您散列密码。
User user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("user")
.build();
System.out.println(user.getPassword());
请记住,以这种方式设置用户只能用于测试,而不能用于生产,这就是官方 API 中不推荐使用 withDefaultPasswordEncoder
的原因。