1

I implemented a basic JPA authentication following this tutorial.

I wanted to create an endpoint /mydetails to display user information (profile info).

What I've tried:

@GetMapping("/mydetails")
public Optional<User> getUser(HttpServletRequest request) {
    Optional<User> foundUser = Optional.ofNullable(userRepo.getUserByUsername(request.getUserPrincipal().getName()));
    return foundUser;
}

Outcome:

{
  "id":1,
  "username":"name.surname@companyname.com",
  "password":"$2a$10$7YzUO6scaC06LV6IgOsSXetFm4/U0WM.UZykhRfQcJBzKacyZFMK",
  "first_name":"John",
  "last_name":"Walker",
  "organization_name":"ABC",
  "role":"Admin",
  "credibility_rating":"100"
}

The problem is that this literally takes out all the information and I want everything except the password.

How could I stop the response from sending the password information?

I am totally new to Spring and have not used Java for many years.

Any insight would be highly appreciated.

rolve
  • 10,083
  • 4
  • 55
  • 75
Cheknov
  • 1,892
  • 6
  • 28
  • 55
  • 1
    why would you even store a password? never store a password, always only a hashed value. If this way doesn't do as you want, you could always use projections, I guess: check this answer. I think it suits your needs. https://stackoverflow.com/questions/22007341/spring-jpa-selecting-specific-columns – Stultuske Feb 02 '23 at 09:21
  • 1
    Additionally, use DTO's as return values instead of the entity itself. If you don't want to do that, just set the password to a null value, before returning it. – Z-100 Feb 02 '23 at 09:23
  • 1
    Additionally to the additionally :D - Instead of wrapping the result of `userRepo.getUserByUsername(...)` in an Optional, just adjust the return type of the interface: `Optional findUserByUsername(String username);`. – Z-100 Feb 02 '23 at 09:25
  • @Stultuske Storing the hashed password is exactly what OP (Spring Security) is doing... – rolve Feb 02 '23 at 09:32
  • @rolve in which case the password isn't returned – Stultuske Feb 02 '23 at 09:41
  • 1
    @Stultuske True, but irrelevant. OP asked how to stop sending "the password information", which includes the password hash. A sensible thing to do anyway, even though the hash should in theory be safe to expose. – rolve Feb 02 '23 at 10:06

1 Answers1

2

It seems you are talking about a REST controller that returns JSON. With the default configuration, Spring Boot uses Jackson to transform objects to JSON. The most simple fix would be to tell Jackson to ignore the password field in your User class:

public class User {
    ...
    @JsonIgnore
    private String password;
    ...
}

See this article for more information.

rolve
  • 10,083
  • 4
  • 55
  • 75