Search code examples
springsecurityhateoas

Spring current user as Hateoas resource


It's my first Spring project. I have a user repository exposed as a RepositoryRestResource. And I have Spring Security set up for very basic authentication. What I would like to do is to return the current user's Hateoas resource from my AuthenticationController without having to maintain a resource assembler. I want to consume the user RepositoryRestResource from inside the AuthenticationController and return the resource as it is. Right now, I have something like this:

@RestController
public class AuthenticationController {

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }
}

I can get the User entity from the principal or with something like:

Resource<User> getCurrentUser(@ModelAttribute User self){...}

And I want to return the user's Hateoas resource instead of the Principal by reaching the repository rest resource from the controller. How can I achieve this or is it a weird thing to ask for?


Solution

  • Retrieve your user entity from the repository using your principal details, for example:

    @BasePathAwareController
    public class MyUserController {
    
      @Autowired UserAccountRepository repository;
    
      @GetMapping("/user")
      @ResponseBody
      public Resource<?> getUser(@AuthenticationPrincipal UserDetails principal, PersistentEntityResourceAssembler assembler) {
    
        if (null==principal) {
          return null;
        }
    
        UserAccount user = repository.findByUsername(principal.getUsername());
        return assembler.toFullResource(user);
      }
    }
    

    Notes: