2013-02-23 19 views
8

मैं नियंत्रक कार्रवाई को सुरक्षित करना चाहता हूं ताकि केवल "व्यवस्थापक" भूमिका वाले उपयोगकर्ता ही हो सकें।
मैं सभी चीज़ों पर भूमिका/सदस्यता प्रदाता का उपयोग नहीं करता हूं।
मैं अब तक इस बनाया:कस्टम प्राधिकरण के लिए 'पास पैरामीटर' जोड़ने के लिए

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"); 
    } 
} 

सूचना है कि मैं "व्यवस्थापक" यहाँ hardcoded।
मैं चाहता हूं कि यह गतिशील हो।
यह अब काम:

[CustomAuthorize] 
     public ActionResult RestrictedArea()... 

लेकिन मैं कुछ इस तरह हैं:

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

उत्तर

19

AuthorizeAttribute पहले से ही Roles संपत्ति जो इस उद्देश्य के लिए इस्तेमाल किया जा सकता है:

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

मैं हो रही है ' यह। रोल 'मान' शून्य ' –

+1

के रूप में क्या आपने' भूमिका 'चर' [कस्टम प्राधिकरण (भूमिकाएं = "व्यवस्थापक")] 'मान को पास किया था? – Zbigniew

+0

हाँ सब कुछ एक ही है –

संबंधित मुद्दे