-1

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}

asu
  • 61
  • 5

1 Answers1

0

I'm guessing that you're using thymeleaf to generate your html because that's the default option in most spring-boot projects, if so - take a look at this example.

Basically you need to pass the information about login error to the model object, and use it in your html template. For example .:

Controller method

model.addAttribute("loginError", true);

Login page template

<p th:if="${loginError}" class="error">Wrong user or password</p>
Kamil Bęben
  • 1,064
  • 8
  • 12
  • Yeah, I'm using Thymeleaf and also you can see that I also use model object to create a error messages for validation fields, like for example if user didnt insert first name while registering etc. But, how will my model know is there error? Please take a look at my github if you can figure out how to implement it, Im trying but no sucess so far https://github.com/sjankdev/budgettracker-final/tree/feature/validate-inputs/src/main/java/com/budgettracker/demo/security/controllers – asu Jan 12 '23 at 17:13
  • I managed to return same page but errors are not appearing – asu Jan 12 '23 at 17:13
  • To be honest i don't see anything wrong with your implementation, perhaps one of the answers to this question (https://stackoverflow.com/questions/48614773/spring-boot-validation-annotations-valid-and-notblank-not-working) will help. – Kamil Bęben Jan 12 '23 at 17:42
  • I have that working, my problem is to check user insert username and password, this for @NotBlank etc works fine, I can show user message if field is empty or doesnt meet requirements, but if use for example enter wrong password I'm being redirected to JSON instead I want to show message on html like for other fields, that is the problem – asu Jan 12 '23 at 17:49
  • I don't see any code in your repository that would report such error - try what's described in this tutorial in "Displaying global errors" section (https://www.baeldung.com/spring-thymeleaf-error-messages) (as that error would be related to both login and password fields) – Kamil Bęben Jan 12 '23 at 17:56
  • That tutorial is regarding errors for fields, like if user doesnt insert age field or insert age lower than 15, I know that works on my code, I have problem to check user credentials – asu Jan 12 '23 at 18:13
  • In the section that I've pointed they've described a way to validate more complex conditions which are not bound to specific fields. – Kamil Bęben Jan 12 '23 at 21:45