Spring security 在创建请求期间在资源属性中使用当前授权的用户
我有一个实体,它有Spring security 在创建请求期间在资源属性中使用当前授权的用户,spring-security,spring-data-rest,Spring Security,Spring Data Rest,我有一个实体,它有MyUser作者属性。我还在自定义授权过程中使用此类来创建MyUserPrincipal实例。(我的灵感来自Callicoder和。) 日志记录过程部分的代码片段: 公共类CustomOAuth2UserService扩展了DefaultOAuth2UserService{ @凌驾 公共OAuth2User loadUser(OAuth2UserRequest userRequest)引发OAuth2AuthenticationException{ //我使用myUserRep
MyUser作者代码>属性。我还在自定义授权过程中使用此类来创建MyUserPrincipal
实例。(我的灵感来自Callicoder和。)
日志记录过程部分的代码片段:
公共类CustomOAuth2UserService扩展了DefaultOAuth2UserService{
@凌驾
公共OAuth2User loadUser(OAuth2UserRequest userRequest)引发OAuth2AuthenticationException{
//我使用myUserRepository加载MyUser实例,然后返回实现OAuth2User、UserDetails的MyUserPrincipal。。。
}
}
例如,现在我有了Book entity的存储库。这本书可以是这样的:
{
"author":"api/authors/42",
"title":"stackoverflow forever"
}
@实体
@Getters//project lombook magic在此
@二传手
公共课堂用书{
私人MyUser作者;
私有字符串标题;
}
我可以使用POST request创建新资源,以处理以下数据:
{
"author":"api/authors/42",
"title":"stackoverflow forever"
}
我的问题:是否可以轻松(无需自定义控制器)使用SecurityContext
中的“authentication.principal.userId”来填写新创建的资源/实体?我想禁止我的API用户发送作者字段。我不知道“自定义控制器”是什么意思,但是/API/books
URI后面的@RestController可以使用@AuthenticationPrincipal
。如果作者id是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
}
}
好的,这看起来很容易理解,尽管在我看来是“自己的控制器”。我会尽量走这条路。