【问题标题】:Claims authorization for specific resources对特定资源的声明授权
【发布时间】:2013-05-01 21:11:21
【问题描述】:

我正在编写一个示例文件存储系统(仅用于 stackoverflow 的示例)。

我当前的域模型如下所示:

public class User
{
    public int ID { get; set; }
    public string LoginIdentifier { get; set; }
    public string Password { get; set; }
}

public class File
{
    public int ID { get; set; }
    public int UserID { get; set; }
    public string FileName { get; set; }
    public byte[] Data { get; set; }
}

我正在编写的用于创建 IPrincipal 的代码:

private static IPrincipal CreatePrincipal(User user)
{
    Debug.Assert(user != null);

    var identity = new GenericIdentity(user.LoginIdentifier, "Basic");

    // TODO: add claims
            identity.AddClaim(new Claim("Files", "Add"));

    return new GenericPrincipal(identity, new[] { "User" });
}

在我的系统中,用户可以添加文件,也可以检索、删除和更新文件,但是需要注意的是用户只能检索和修改自己的文件(其中File.UserID 应与身份匹配登录用户)。

我的文件控制器如下所示。

[Authorize]
public class FilesController : ApiController
{
    private readonly FileRepository _fileRepository = new FileRepository();

    public void Post(File file)
    {
        // not sure what to do here (...pseudo code...)
        if (!CheckClaim("Files", "Add"))
        {
            throw new HttpError(HttpStatusCode.Forbidden);
        }

        // ... add the file
        file.UserID = CurrentPrincipal.UserID; // more pseudo code...

        _fileRepository.Add(file);
    }

    public File Get(int id)
    {
        var file = _fileRepository.Get(id);

        // not sure what to do here (...pseudo code...)
        if (!CheckClaim("UserID", file.UserID))
        {
            throw new HttpError(HttpStatusCode.Forbidden);
        }

        return file;
    }
}

也许使用Claims 不是适合这项工作的工具,但希望这能说明问题。

我应该如何连接我的控制器以确保当前登录的用户有权执行特定操作,更具体地说,某些资源?

【问题讨论】:

    标签: .net authentication asp.net-web-api authorization claims-based-identity


    【解决方案1】:

    我不确定索赔是否适合您正在做的事情。您真正想要表示的是权​​限。声明通常代表身份属性,例如用户名、电子邮件或它所属的角色,但不代表权限。您可以使用声明来表示权限,但您可能需要大量权限,具体取决于您的应用程序有多大。一种典型的方法是将角色映射到一组权限(在您的情况下,添加文件将是一个权限)。您还可以创建从 AuthorizeAttribute 派生的自定义授权过滤器,以检查当前主体是否具有执行操作的正确权限。该过滤器可能会接收执行操作所需的权限作为参数。

    【讨论】:

    • 在这种情况下,我认为声明将是UserID
    • 是的,这是有道理的。您还可以拥有代表用户角色的声明。然后将角色映射到一组权限。例如,Admin => 添加文件、删除文件等
    【解决方案2】:

    Pablo 是对的 - 声明描述了身份。不过,您使用该身份来做出授权决定。有一个单独的抽象,称为 ClaimsAuthorizationManager。

    看看这里: http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/

    【讨论】:

    • 我在发布这个问题之前阅读了这篇文章,我关心的部分(以及我不明白的部分)是ClaimsAuthorization.CheckAccess(“Get”, “CustomerId”, id.ToString()); 声明。具体来说,如何实现这样的事情(在我的场景中)?
    • 您可以将“modify/whatever”、“file”和文件所有者传递给声明 authZ 管理器。然后,这将检查当前主体是否与文件所有者匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多