2016-10-11 57 views
2

我知道我可以通過用AuthorizeAttribute()裝飾它來限制對控制器(或其成員)的訪問。根據用戶聲明授權訪問控制器

隨着ASP身份的出現和朝着更多「基於索賠的」世界邁進,我希望找到相應的屬性。類似於:

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

儘管我確信這會建立在身份識別的基礎上,但是我所有的搜索都已經空白。

如果不存在,我該如何推出自己的?

+0

我有在生產實施在此之前發佈的概念證明索賠授權。您可以查看過濾器:https://github.com/trailmax/ClaimsAuthorisation/blob/master/ClaimsAuth/Infrastructure/Identity/ClaimsAuthorisationFilter.cs,並想知道其他回購協議。 – trailmax

回答

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()); 
    } 
} 
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 
{ 
}