在创建请求期间在资源属性中使用当前授权的用户

时间:2020-04-07 08:41:34

标签: spring-security spring-data-rest

我有一个具有MyUser author;属性的实体。我还在自定义授权过程中使用此类来创建MyUserPrincipal实例。 (我从Callicoder blog postrepository得到了启发。)

日志记录程序部分的片段:

public class CustomOAuth2UserService extends DefaultOAuth2UserService {
    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        // He I use myUserRepository, to load MyUser instance and than return MyUserPrincipal which implements OAuth2User, UserDetails...
    }
}

现在我有了Book实体的存储库。书可以是这样的:

@Entity
@Getters // project lombook magic here
@Setters
public class Book {
    private MyUser author;
    private String title;
}

我可以使用对http://localhost/api/books的POST请求,使用如下数据创建新资源:

{
 "author":"api/authors/42",
 "title":"stackoverflow forever"
}

我的问题:是否可以轻松地(无需自定义控制器)使用SecurityContext中的“ authentication.principal.userId”来填写作者新创建的资源/条目?我想完全禁止我的API用户发送作者字段。

1 个答案:

答案 0 :(得分:1)

好吧,我不知道您所说的“自定义控制器”是什么意思,但是/api/books URI后面的@RestController可以使用@AuthenticationPrincipal。这样,如果它是MyUserPrincipal的一部分,则不必再发送您的作者ID。

@PostMapping("/api/books")
public SomeDTO saveBook(@AuthenticationPrincipal MyUserPrincipal principal) {

  if (principal != null) { // user is logged in and not e.g. anonymous
     // principal.getId(); use this to save your book
  }

}