Spring当前用户作为Hateoas资源

问题描述 投票:1回答:1

这是我的第一个春季项目。我将一个用户存储库公开为RepositoryRestResource。我已经为最基本的身份验证设置了Spring Security。我想要做的是从我的AuthenticationController返回当前用户的Hateoas资源,而不必维护资源汇编程序。我想从AuthenticationController内部使用用户RepositoryRestResource并按原样返回资源。现在,我有这样的事情:

@RestController
public class AuthenticationController {

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

我可以从委托人那里获得用户实体,或者使用以下内容:

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

我希望通过从控制器访问存储库rest资源来返回用户的Hateoas资源而不是Principal。我怎样才能实现这一点,或者要求它是一件奇怪的事情?

spring security hateoas
1个回答
0
投票

使用您的主体详细信息从存储库中检索您的用户实体,例如:

@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);
  }
}

笔记:

© www.soinside.com 2019 - 2024. All rights reserved.