I am newbie in Spring Boot.
I'd like to know how can I validate the Credentials DTO before the Authentication in Spring Boot?
I have this controller:
@PostMapping
public ResponseEntity<TokenDTO> generateTokenJwt(@Valid @RequestBody CredentialsDTO credentials, BindingResult result)
throws AuthenticationException {
TokenDTO response = new TokenDTO();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
credentials.username, credentials.password);
Authentication authentication = authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(credentials.username);
String token = jwtTokenUtils.getToken(userDetails);
response.token = token;
return ResponseEntity.ok(response);
}
The Credentials DTO is:
public class CredentialsDTO {
@NotEmpty
public String username;
@NotEmpty
public String password;
}
So, when I execute the POST like this:
curl -i -X POST \
-H "Accept:application/json" \
-H "Content-Type:application/json" \
-d \
'{
"username": "",
"password": "123456"
}' \
'http://localhost:8080/api/login'
I'd like to show a 422 error telling that the username propertie should not be empty, but, what is happening is that authentication is being done first and the error returned is 401.