温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - Spring Security
java security spring spring-boot spring-security

java - Spring 安全

发布于 2020-03-27 10:58:50

假设使用Java 8和Spring Boot 2,我有一个像下面这样的最小RESTful控制器...

@RestController
class MyController {

    @Autowired
    private PostService service;    

    @GetMapping
    public Post get() {

        return service.getLatest();
    }
}

我已经使用Spring Security模块成功保护了此路由。现在,我只允许资源所有者访问此资源。对于资源所有者,我的意思是创建者或简单地说:

Post myPost = new Post();
...
myPost.getCreator().equals(currentUser); // Should be true when access is granted

我发现了很多有关基于角色的访问的信息,但几乎没有用于检查所有权的信息……当然,我可以在控制器中放置if语句并抛出异常,但是我打算使用类似Spring的基于表达式的访问控制之类的东西

还有其他想法吗?有人对资源的所有权检查有一个好主意或示例吗?

查看更多

查看更多

提问者
0x1C1B
被浏览
152
Joeri Boons 2019-07-04 17:17

对于简单的get操作,您只需返回链接到当前登录用户的帖子即可

@GetMapping
public Post getPost(Authentication authentication) {
    return service.getPostByUser(authentication.getName());
}

要更新现有帖子,您可以在PreAuthorize中检查创建者是否是登录用户。authentication.getName()在我的示例中返回一封电子邮件

@PutMapping
@PreAuthorize("#post.getCreator() == authentication.getName()")
public void update(@RequestBody Post post, Authentication authentication) {
    service.updatePost(post);
}

@Component方法的基本示例

@Autowired
private CreatorCheck creatorCheck;

@PutMapping
@PreAuthorize("@creatorChecker.check(#post,authentication)")
public void update(@RequestBody Post post, Authentication authentication) {
    service.updatePost(post);
}

和组件。可以扩展以检索原始帖子并检查该创建者。

@Component
public class CreatorCheck {

    public boolean check(Post post, Authentication authentication) {
       return post.getCreator().equals(authentication.getName());
    }
}

有关更全面的教程,请查看0x1C1B找到的教程链接