I followed some tutorial for Spring Boot Security, and in that tutorial the guy is not creating a Frontend so his message for wrong credentials when user is trying to log in are in JSON. I did some changes to my own and created a page for login and registration, but I have problem to show errors when user insert wrong credentials.
This is method that show me JSON when user insert wrong data:
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final Map<String, Object> body = new HashMap<>();
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
body.put("error", "Unauthorized");
body.put("message", authException.getMessage());
body.put("path", request.getServletPath());
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
And in my controller I have this:
@PostMapping("/login")
@Transactional
public String login(@Valid @ModelAttribute("login") LoginRequest loginRequest, BindingResult result, HttpServletResponse response, Model model) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);
boolean thereAreErrors = result.hasErrors();
if (thereAreErrors) {
model.addAttribute("login", loginRequest);
return "login_form";
}
model.addAttribute("login", loginRequest);
response.addHeader(HttpHeaders.SET_COOKIE, jwtCookie.toString());
return "redirect:/api/test/homePage";
}
So far its return error messages (validation field) on HTML if user doesn't populate fields, but if user enter wrong data I'm getting JSON {"path":"/api/auth/login","error":"Unauthorized","message":"Bad credentials","status":401}