【问题标题】:Using Authorization claims with context dependent roles将授权声明与上下文相关角色一起使用
【发布时间】:2016-02-29 06:43:10
【问题描述】:

首先,我是 C# 授权领域的新手。我在IPrincipalIIdentity Claim 上阅读了很多内容,但我无法将其映射到我当前的应用程序。

考虑:我有三个用户:Alice、Bob 和 Charlie,他们都有文件。 假设我以 Alice 和 Bob 的身份登录,而 Charlie 与 Alice 共享他们文件的权限。现在,Bob 向 Alice 授予了 r/w 访问权限,但 Charlie 只授予了 Read 访问权限。

API 的公开方式是通过 WebApi 作为 REST 端点(属性路由)。理想情况下,我会在端点上放置另一个属性,并声明它需要例如:

GET    /{user}/files/{fileId} // Gets: Claim("files", "read")
DELETE /{user}/files/{fileId} // Gets: Claim("files", "delete")

这里的问题是我不知道如何评估这些声明,因为它们依赖于user 的值。在示例中,user 是 Bob 或 Charlie,而我以 Alice 身份登录。

谁能帮我看看如何建立这样的系统?我会对一些特定领域的术语或一篇好的博文感到满意。

【问题讨论】:

  • 如果您认为有必要,请向我寻求说明或建议一种完全不同的方法 =)

标签: c# rest asp.net-web-api authorization claims


【解决方案1】:

有一个很好的关于声明授权的教程: http://bitoftech.net/2015/03/31/asp-net-web-api-claims-authorization-with-asp-net-identity-2-1/

但您也可以使用基于角色的方法并检查用户是否可以使用您的业务逻辑访问文件。

您无需在 API 的路由中指定用户。保持您的路线通用:

GET    /files/{fileId}
DELETE /files/{fileId} 

首先,您可以创建一个 BaseApiController 来保存控制器的用户信息:

public class BaseApiController : ApiController
{
    public Guid UserID { get; set; }
}

您可以使用自定义授权属性装饰您的 GET 和 DELETE 方法:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class CustomAuthorize : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        IPrincipal principal = ((BaseApiController)actionContext.ControllerContext.Controller).User;
        //is the user already logged in on the system. This would work perfectly if you have a cookie in your web application authorizing the user
        bool isAuthenticated = principal != null && principal.Identity.IsAuthenticated;

        if (!isAuthenticated)
        {
            // Deny request or you could also check the request headers for an authorization token
            return false;
        }

        // Save UserID to be used later in your controllers
        ((BaseApiController)actionContext.ControllerContext.Controller).UserID = UserID;

        // Authorize user, or you could also check if the user has the correct roles 
        return true;
    }
}

在您的控制器中:

public FilesController : BaseApiController 
{
    [CustomAuthorize]
    public HttpResponseMessage Get(int fileID) 
    {
        return filesAccess.getFile(fileID, UserID);
    }
}

【讨论】:

  • Soo,你怎么知道你现在看的是 Bob 还是 Charlie,因为它已经不在路线上了?
  • 在我的示例中,这将是“UserID”,它是一个 Guid,但它可能只是一个包含 Bob 或 Charlie 的字符串。
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2018-11-01
  • 2010-10-21
  • 1970-01-01
  • 2016-06-21
  • 2023-03-19
  • 2017-09-10
  • 1970-01-01
相关资源
最近更新 更多