0

I have my own UserDetails implementation

public class CustomUserDetails extends org.springframework.security.core.userdetails.User {
     private UserEntity userEntity;
...
}

my login implementation

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
...

@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    Optional<UserEntity> userOptional;
    if(username.contains("@")) {
        userOptional = userRepository.findByEmailIgnoreCaseAndEnabledTrue(username);
    } else {
        userOptional = userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username);
    }

    ...

    return new CustomUserDetails(userOptional.get().getUsername(),
                                 userOptional.get().getPassword(),
                                 grantedAuthorities,
                                 userOptional.get());
}

I get an entity using the service

@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {

    @Override
    public UserEntity getUser() {
        return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserEntity();
    }
}

and assign a new password to the site marked with the @Transactional annotation, but it does not update in the database

@Service("userPersistenceService")
@Transactional
public class UserPersistenceServiceImpl implements UserPersistenceService {
    /**
 * {@inheritDoc}
 */
@Override
public void updatePassword(
        @NotNull @Valid final ChangePasswordDTO changePasswordDTO
) throws ResourceNotFoundException, ResourceBadRequestException {
    log.info("Called with changePasswordDTO {}", changePasswordDTO);

    final UserEntity user = this.authorizationService.getUser();

    if(!EncryptUtils.matches(changePasswordDTO.getOldPassword(), user.getPassword())) {
        throw new ResourceBadRequestException("The entered password doesn't match the old password");
    }

    user.setPassword(EncryptUtils.encrypt(changePasswordDTO.getNewPassword()));
}
}

I would like that during user.setPassword(...) immediately automatically update data for entities in the database. That's why I added the @Transactional annotation. But it does not work. Why?

Alan Hay
  • 22,665
  • 4
  • 56
  • 110
JONKI
  • 535
  • 5
  • 10
  • 24

0 Answers0