Я переполнен стеком, пытаясь выяснить, почему возникает эта проблема, но не могу найти ответ.
Это мои настройки:
SecurityConfig
@Autowired
private IUserService userService;
@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http.
authorizeRequests().
antMatchers("/api/**"). // if you want a more explicit mapping here
//anyRequest().
// authenticated().antMatchers("/api/users/**").
permitAll().
and().
httpBasic().
and().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().csrf().disable();
// @formatter:on
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
Метод создания UserService:
@Override
public User create(User u) {
User newUser = new User();
newUser.setUsername(u.getUsername());
newUser.setEmail(u.getEmail());
newUser.setPhoneNum(u.getPhoneNum());
newUser.setPassword(passwordEncoder.encode(u.getPassword()));
// Add default roles
Role userRole = roleService.findByName("ROLE_USER");
newUser.setRoles(Sets.<Role>newHashSet(userRole));
dao.save(newUser);
return newUser;
}
Обратите внимание, что пользователь реализует UserDetails, а IUserService реализует UserDetailsService.
Основываясь на других статьях, здесь приведена дополнительная информация:
I 'я не пытаюсь сделать OAUTH, поэтому, пожалуйста, не рекомендую также кодировать секрет клиента
Я проверил свою базу данных, это VARCHAR (68), поэтому я считаю, что есть достаточно места для хранения закодированного пароля.
База данных действительно хранит зашифрованный пароль (я посмотрел и его не простой текст)
Вот некоторые журналы отладки из запроса, который отклоняется:
DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'wowz'
23:17:57.187 [http-nio-8082-exec-8] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
23:17:57.471 [http-nio-8082-exec-8] WARN o.s.s.c.bcrypt.BCryptPasswordEncoder - Encoded password does not look like BCrypt
23:17:57.472 [http-nio-8082-exec-8] DEBUG o.s.s.a.d.DaoAuthenticationProvider - Authentication failed: password does not match stored value
23:17:57.472 [http-nio-8082-exec-8] DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Authentication request for failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
23:17:57.472 [http-nio-8082-exec-8] DEBUG o.s.s.w.a.DelegatingAuthenticationEntryPoint - Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
23:17:57.473 [http-nio-8082-exec-8] DEBUG o.s.s.w.a.DelegatingAuthenticationEntryPoint - No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@42da9490
23:17:57.473 [http-nio-8082-exec-8] DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@115f4872
23:17:57.473 [http-nio-8082-exec-8] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Также обратите внимание, что это безопасность для REST API, а не для приложения MVC