在Spring Security中基于某种所有权设置用户角色 [英] Setting user roles based on some kind of ownership in Spring Security

查看:72
本文介绍了在Spring Security中基于某种所有权设置用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于Spring的应用程序中,我目前具有基本角色,例如ADMIN和USER.

In my Spring-based application, I currently have basic roles such as ADMIN, and USER.

是否可以定义用户角色(例如PHOTO_UPLOADER),该角色继承自USER,还可以添加检查用户是否实际上是照片的所有者?

Is it possible to define a user role such as PHOTO_UPLOADER, which inherits from USER, but also adds a check whether the user making the call is actually the owner of the photo?

我厌倦了在控制器动作中一遍又一遍地写相同的if (currentUser.id == photo.uploader.id).它也适用于其他实体.

I am tired of writing the same if (currentUser.id == photo.uploader.id) in my controller actions over and over again. It applies to other entities as well.

推荐答案

您可以使用Tomasz Nurkiewicz建议的ACL来处理它.但是Spring Securitz ACL很复杂,而且文档记录很差. (我所知道的最好的资源是这本书: Spring Security 3-由Spring Security的作者编写)

You can handle it with ACLs like Tomasz Nurkiewicz suggested. But Spring Securitz ACLs are complex and poor documented. (The best resource I know for it is this Book: Spring Security 3 - by the authors of Spring Security)

但是,如果您真的只需要这个简单的if (currentUser.id == photo.uploader.id)测试,那么我建议您使用另一种技术.

But If you really need only this simple if (currentUser.id == photo.uploader.id) test, then I would recommend an other technique.

可以增强方法安全性表达式,您可以在@PreAuthorize批注中使用它们.喜欢:

It is possible to enhance the method security expressions you can use them in @PreAuthorize annotations. Like:

@PreAuthorize("isPhotoOwner(#photo)")
public void doSomething(final Photo photo) {

要实现这样的表达式isPhotoOwner,核心真的很简单:

To implement such an expression isPhotoOwner the core is really simple:

public class ExtendedMethodSecurityExpressionRoot extends MethodSecurityExpressionRoot {

    public ExtendedMethodSecurityExpressionRoot(final Authentication a) {
        super(a);
    }

    /**
     * 
     */
    public boolean isPhotoOwner(final Photo photoObject) {
        if (photoObject == null) {
            return false;
        }

        Photo photo = (photo) photoObject;
        return photo.getCreator().getLogin().equals(authentication.getName());
    }
}

不幸的是,还有一些其他工作来注册ExtendedMethodSecurityExpressionRoot. --- 我现在没有时间,如果您愿意尝试这种方法,请留下评论,剩下的我将予以介绍

Unfortunaly there is some addtional work to to register the ExtendedMethodSecurityExpressionRoot. --- I have no time at the moment, if you are willing to try this approach, then leave a commment, and I will descripe the rest

这篇关于在Spring Security中基于某种所有权设置用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆