Spring security 使用用户名PasswordAuthenticationToken和PasswordEncoder登录

Spring security 使用用户名PasswordAuthenticationToken和PasswordEncoder登录,spring-security,Spring Security,我没有编码我的密码,直到现在,因此在底部的代码工作良好。 现在,在注册时使用PasswordEncoder对密码进行编码,因此哈希密码应该在数据库中 我现在的问题是,现在如何使用用户名密码身份验证令牌。如果我传递了编码密码,登录就会失败?还有其他类可以输入编码密码吗 final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(usernameOrEmailAddress, pa

我没有编码我的密码,直到现在,因此在底部的代码工作良好。 现在,在注册时使用PasswordEncoder对密码进行编码,因此哈希密码应该在数据库中

我现在的问题是,现在如何使用用户名密码身份验证令牌。如果我传递了编码密码,登录就会失败?还有其他类可以输入编码密码吗

final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(usernameOrEmailAddress, password);
这是我的登录方法:

@RequestMapping(value = "/login", method = { RequestMethod.POST }, consumes = "application/json;charset=utf-8")
public UserTransferObject login(final @RequestBody LoginData loginData) throws BusinessException {

    final String usernameOrEmailAddress = loginData.getUsername();
    final String password = loginData.getPassword();

    // passwordEncoded does not work here
    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(usernameOrEmailAddress, password);
    try {
        final Authentication authentication = this.authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        final String message = messageByLocaleService.getMessage("login.error"); // key declared in frontend project
        throw new BusinessException(message, "400", e.getCause());
    }

    final UserDetails userDetails = this.userDetailsService.loadUserByUsername(usernameOrEmailAddress);
这里我遇到了一个问题,当我使用用户编码的密码时,die AuthenticationManager无法进行身份验证-我得到了一个BadCredentialsException异常:

final Authentication authentication = this.authenticationManager.authenticate(token);
[编辑]

我意识到我还有另一个问题。在方法login中输入用户名和普通密码,然后我使用PasswordEncoder计算哈希和salt。authenticationManager.authenticate
从数据库加载用户,但在数据库中,用户有另一个哈希密码,因为salt在创建时不同
实际上,我解决这个问题的方法是禁用salt,但安全性是佩戴者。如果有任何提示可以解决这个问题,我将不胜感激。

要计算哈希和salt,您应该使用数据库中的salt,您可以使用类
ReflectionSaltSource
通过反射获取salt,并在您的用户实体中使用此方法生成密码。
public void encodePassword(PasswordEncoder PasswordEncoder){if(salt==null){SecureRandom sr=newSecureRandom();byte[]saltByte=new byte[16];sr.nextBytes(saltByte);salt=new Base64().encodeToString(saltByte);}password=PasswordEncoder.encodePassword(password,salt);}