春のセキュリティ - 所有権ベースのアクセス

0x1C1B:

レッツは、私は、Java 8と春ブーツ2を使用する方法により、以下のように最小限のRESTfulなコントローラをしたと言います...

@RestController
class MyController {

    @Autowired
    private PostService service;    

    @GetMapping
    public Post get() {

        return service.getLatest();
    }
}

私は正常に春のセキュリティモジュールを使用して、このルートを確保してきました。今私は、このリソースにのみリソースの所有者のアクセスを許可したいです。リソースの所有者で、私は、作成者を意味するか、それがシンプルと言って:

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

私は、役割ベースのアクセスについて多くのことを発見しませんが、所有権を確認するため、ほとんど何も...もちろん、私は、コントローラのif文の内側に配置し、例外をスローする可能性が、私は春のようなものを使用することを意図し、式ベースのアクセス制御を

他のアイデア?誰かがリソースの所有権の確認のために良いアイデアや例を持っていますか?

Joeriブーンズ:

簡単なget操作のためにあなたは自分の現在にリンクされている投稿がログインしているユーザーを返すことができます

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

作成者がログインしているユーザーであれば、既存のポストを更新するためには、事前認証以内に確認することができます。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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=227758&siteId=1