如何在用户注册后使用bcrypt为Spring Boot设置自动登录,获取Bad Credentials错误

时间:2017-11-05 07:46:49

标签: spring spring-mvc spring-boot spring-security bcrypt

我有一个问题,关于如何在用户注册Spring Boot应用程序后自动登录用户。用户的密码使用Bcrypt保存到MySQL DB中。

这是我必须正确创建和保存新用户的方法,它似乎工作正常:

@Autowired
private UserRepository userRepository;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

public User save(User user, Role role) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setRoles(new HashSet<>(Arrays.asList(role)));
    userRepository.save(user);
    return user;
}

这是我尝试登录新创建的用户时执行的方法:

 public boolean login(String username, String password) {

    //password is plaintext and is what was POST-ed from the HTML form

    UserDetails userDetails = loadUserByUsername(username);

    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
            new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    authenticationManager.authenticate(usernamePasswordAuthenticationToken);

    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        logger.debug(String.format("Logged in %s successfully!", username));
        return true;
    } else {
        logger.debug(String.format("Failed to login %s", username));
        return false;
    }
}

现在,当它出现在线上时:

authenticationManager.authenticate(usernamePasswordAuthenticationToken);

它会一直抱怨:

00:36:47.635 [http-nio-5000-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - Could not complete request
org.springframework.security.authentication.BadCredentialsException: Bad credentials

我觉得这很奇怪。在我的WebSecurityConfigurerAdapter中,我有这些设置:

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userServiceManager).passwordEncoder(bCryptPasswordEncoder());
}

有人可以告诉我,如果我错过了什么吗? 感谢

0 个答案:

没有答案