根据用户声明授权访问控制器

时间:2016-10-11 14:40:42

标签: c# asp.net asp.net-mvc asp.net-identity

我知道我可以通过使用AuthorizeAttribute()进行装饰来限制对控制器(或其成员)的访问。

随着ASP身份的出现,并转向更多基于声明的声明"世界我想找到等价的属性。类似的东西:

 [ClaimAuthorize(Permission="CanCreateCustomer")]
 public ActionResult CreateCustomer()
 {
     return View();
 }

虽然我确信这会以身份为中心,但我所有的搜索都是空白。

如果它不存在,我该如何自行滚动?

2 个答案:

答案 0 :(得分:1)

你必须自己动手。从那时起,您可以根据需要自定义它。

您必须扩展授权属性。

public class ClientAuthorize : AuthorizeAttribute
{
    public new String Roles { get; set; }
    public String RequiredRights { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return CustomAuthorizeLogicReturnsBool(Roles, RequiredRights);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //filterContext.Result = new HttpUnauthorizedResult();
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
    }


}

用法

[ClientAuthorize(Roles = "ClientUser", RequiredRights = "SaveAdmin,KillAdmin")]
public class AdminController : Controller
{
}

答案 1 :(得分:0)

您可能应该为此提出文档请求,但为了让您入门,您可以实现IAuthenticationFilter,注册它,然后用以下内容装饰您的控制器:[Authorize(Roles = "CanCreateCustomer")]

public class CustomAuthenticationAttribute : Attribute, System.Web.Http.Filters.IAuthenticationFilter
{
    public bool AllowMultiple
    {
        get
        {
            return true;
        }
    }

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
            context.Principal = //get principal here, based on your implementation
    }

    public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        await Task.FromResult(0);
    }
}

注册:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Filters.Add(new CustomAuthenticationAttribute ());
    }
}