我可以在DaoAuthenticationProvider实现中获取用户dao,但似乎无法更新同一对象。我想增加登录失败的访问失败次数,但spring最终会引发异常。
我尝试自动装配实体管理器并独立创建事务并保存用户对象,但无济于事。
这是相关的服务方法调用:
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:提交事务时出错]
答案 0 :(得分:0)
这是预期的行为。您可以在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);
}