2013-02-23 14 views
8

Chcę zabezpieczyć działanie kontrolera, aby mogli dostać się tylko użytkownicy z rolą "Admin".
Nie używam dostawcy roli/członkostwa w ogóle, wszystko jest niestandardowe.
zrobiłem to do tej pory:Jak dodać "parametr pass" do niestandardowego AuthorizeAttribute

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext);    
     if (!isAuthorized) 
      return false; 

     string username = httpContext.User.Identity.Name; 

     UserRepository repo = new UserRepository(); 

     return repo.IsUserInRole(username, "Admin"); 
    } 
} 

Zauważ, że sztywno „Administrator” tutaj.
Chcę, żeby to było dynamiczne.
Ta praca teraz:

[CustomAuthorize] 
     public ActionResult RestrictedArea()... 

Ale chcę coś takiego:

[CustomAuthorize(Roles = "Admin")] 
     public ActionResult RestrictedArea() 

Odpowiedz

19

AuthorizeAttribute już Roles nieruchomości, które mogą być wykorzystane do tego celu:

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext);    
     if (!isAuthorized) 
     { 
      return false; 
     } 

     string username = httpContext.User.Identity.Name; 

     UserRepository repo = new UserRepository(); 

     return repo.IsUserInRole(username, this.Roles); 
    } 
} 
+0

Dostaję ' this.Roles' value as 'null' –

+1

Czy przekazałeś wartość zmiennej' Role' '[CustomAuthorize (Roles =" admin ")]'? – Zbigniew

+0

tak Wszystko jest takie same –

Powiązane problemy