我可以在DaoAuthenticationProvider实现中获取我的用户dao,但我似乎无法更新同一个对象。我想在不成功的登录时增加访问失败计数,但是春天最终会抛出异常。
我尝试过自动连接实体管理器并独立创建事务并保存用户对象但无济于事。
以下是相关的服务方法调用:
public void resetPassowrdAttempts(CorAclUser user) {
user.setAccessfailedcount(BigDecimal.valueOf(1));
userRepository.save(user); //Exception here
}
以下是DAO身份验证提供程序中的重写方法。我还没有覆盖任何其他方法。
protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication){
CorAclUser aclUser = aclUserRepository.findById_UsernameAndId_UserTenantCode(userDetails.getUsername(),Constants.TENANT_CODE).orElseThrow(
() -> new UsernameNotFoundException("Invalid username or password."));
if(!aclUser.getActiveFlag())
throw new NotFoundException(ExceptionResponseCodes.USER_NOT_FOUND, "User is deactivated");
if(userDetails.getAuthorities()!=null) {
if(verifyHash(authentication.getCredentials().toString(),aclUser.getPasswordhash()) ) {
userService.resetPassowrdAttempts(aclUser);
}else {
throw new BadCredentialsException("Password is incorrect!");
}
}else {
throw new BadCredentialsException("user does not have any privileges");
}
}
这是错误日志:
[ate.internal.ExceptionMapperStandardImpl]:HHH000346:托管刷新期间出错[org.springframework.security.core.userdetails.User无法强制转换为com.tlx.configurations.security.CustomUserDetails]
处理错误:TransactionSystemException,无法提交JPA事务;嵌套异常是javax.persistence.RollbackException:提交事务时出错
已解决[org.springframework.transaction.TransactionSystemException:无法提交JPA事务;嵌套异常是javax.persistence.RollbackException:提交事务时出错]
这是预期的行为。您可以在catch块中更新失败的登录尝试计数器。以下是您的示例代码:
try {
// Perform the actual authentication.
super.additionalAuthenticationChecks(userDetails, authentication);
// Reset login attempts number on successful login.
user.setLoginAttemptsNumber(0);
} catch (final BadCredentialsException e) {
// Increase the number of unsuccessful attempts.
user.setLoginAttemptsNumber(user.getLoginAttemptsNumber() + 1);
if (user.getLoginAttemptsNumber() < maxLoginAttemptsNumber - 1) {
throw new BadCredentialsException(String.format("Incorrect username or password. Attempt %d of %d.",
user.getLoginAttemptsNumber(), maxLoginAttemptsNumber), e);
}
} finally {
userDao.save(user);
}