Ad

Create Custom Messages For Expired And Locked User

I want to return custom message if user during authentication process is locked or expired. I tried to implement this:

@Service
public class UserDetailsHandler implements UserDetailsService {

    @Autowired
    private UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final Optional<Users> user = usersService.findByLogin(username);

        if (!user.isPresent()) {
            throw new UsernameNotFoundException("User '" + username + "' not found");
        }

        return user
            .map(value -> {
                return new User(
                        value.getLogin(),
                        value.getEncryptedPassword(),
                        value.getEnabled(),
                        hasAccountExpired(value.getExpiredAt()),
                        hasPasswordExpired(value.getPasswordChangedAt()),
                        hasAccountLocked(value.getLockedAt()),
                        Collections.singleton(new SimpleGrantedAuthority(value.getRole().getAuthority()))
                );
            }).orElseThrow(() -> new UsernameNotFoundException("User with username " + username + " not found"));
    }

    private boolean hasAccountExpired(LocalDateTime account_expired_at) {

        return account_expired_at == null;
    }

Full code: GitHub

The question is how to create handlers which return some custom message if the validation returns true value for statuses user locked or user expired?

Ad

Answer

The best option for you is:

  1. Implement Spring UserDetails in your entity Users.
  2. Check in loadUserByUsername if the user has been locked, etc using Spring AccountStatusUserDetailsChecker class.
  3. Add into your EngineExceptionHandler the required methods to manage those exceptions: LockedException, AccountExpiredException, etc

You will see examples of above points in the following links:

Point 1

Point 2

Points 2-3

Ad
source: stackoverflow.com
Ad