mọi người cho em hỏi , sao valid của em nó ko hoạt động như mong muốn ạ ?
ở console thì in ra
Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0]
phía postman với dạng json là
{
“email”:null,
“numberPhone”:“test”,
“userName”:“test”,
“password”:“test”
}
và trả về status 403 bidden
@RestController
@RequestMapping("/api/v1/public/auth")
public class SignUpAPI {
@Autowired
@Qualifier("AuthenticationImplementation")
AuthenticationServiceAPI authenticationServiceAPI;
@PostMapping("/signup")
public ResponseEntity<?> signup(@Valid @RequestBody SignupRequest signupRequest) {
return authenticationServiceAPI.signUp(signupRequest);
}
}
@Data
public class SignupRequest {
@NotNull(message = "Email is null")
@NotBlank(message = "Email is blank")
private String email;
private String numberPhone;
private String userName;
private String password;
private Set<String> listRoles;
}
public interface AuthenticationServiceAPI {
ResponseEntity<String> signUp( SignupRequest signupRequest);
LoginResponse login(LoginRequest loginRequest);
}
@Service(“AuthenticationImplementation”)
@Validated
public class AuthenticationImplementation implements AuthenticationServiceAPI {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JsonWebTokenProvider jsonWebTokenProvider;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Override
public ResponseEntity<String> signUp( SignupRequest signupRequest) {
if (userService.existsByUsername(signupRequest.getUserName())) {
return ResponseEntity.badRequest().body("Name is duplicated");
}
if (userService.existsBynumberPhone(signupRequest.getNumberPhone())) {
return ResponseEntity.badRequest().body("Number phone is duplicated");
}
if (userService.existsByEmail(signupRequest.getEmail())) {
return ResponseEntity.badRequest().body("Email is duplicated");
}
Users user = new Users();
user.setEmail(signupRequest.getEmail());
user.setNumberPhone(signupRequest.getNumberPhone());
user.setUsername(signupRequest.getUserName());
user.setPassword(passwordEncoder.encode(signupRequest.getPassword()));
Set<Roles> listRoles = new HashSet<>();
Roles userRole = roleService.findByRoleName(ERole.ROLE_USER).orElseThrow(() -> new RuntimeException("Error : Role user is not found"));
listRoles.add(userRole);
user.setListRoles(listRoles);
userService.save(user);
return ResponseEntity.ok(new String("User signed up successfully!"));
}
@Override
public LoginResponse login(LoginRequest loginRequest) {
// authenticate requested user information
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()
)
);
/**
* If no exception occurs, the information is valid
* Set authentication information into Security Context
*/
SecurityContextHolder.getContext().setAuthentication(authentication);
CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal();
// return jwt for user
String jwt = jsonWebTokenProvider.generateToken((CustomUserDetails) authentication.getPrincipal());
List<String> listRoles = customUserDetails.getAuthorities().stream()
.map(item -> item.getAuthority()).collect(Collectors.toList());
/**
* special line code for java swing
*/
PasswordManager.getInstance().setPassword(customUserDetails.getPassword());
return new LoginResponse(jwt,
"Bearer",
customUserDetails.getUser().getEmail(),
customUserDetails.getUser().getNumberPhone(),
customUserDetails.getUsername(),
listRoles.toString());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}
em có thử sang 1 api khác , gọi trực tiếp ko thông qua interface nào và valid thành công
nhưng riêng code trên thì bị lỗi như trên , mong mọi người giúp đỡ ạ