ASP.NET MVC 2 Authorize-カスタムAuthorizeの実装


ASP.NET MVC 2 Authorize-カスタムAuthorizeの実装


 
 
本文は主に転載して、この小さい例を通じて簡単にあなたのAuthorize権限の制御をカスタマイズすることができて、私は特にASPを理解していないためです.NET WebFormのMemberShipの実装メカニズムは、カスタマイズの性能がクリアされているかどうかは言えませんが、現在はカスタマイズが使いやすいです.
 
 
変換元:
=====================================================================
 

ASP.NET MVC 2ではカスタムAuthorizeAttributeを使用して組み込まれたメンバーシップ/ロールメカニズムを迂回


//すべてのオリジナル文章の転載は作者とリンク//blackboycpp(AT)gmailを明記してください.com//QQ群:135202158
ありがとうDSO athttp://stackoverflow.com/users/38087/DSO
ASP.NET MVC 2では、Authorize Filterを使用してコンテンツへのアクセスを制限できます.
view plain copy to clipboard print ?
[Authorize]  
public class MyController : Controller  
{   
   // ...   
}  
//または[Authorize(Roles="Admin")]  
public class MyController : Controller  
{   
   // ...   
}  
 
ただし、Membership/Roleメカニズムを使用することが前提です.私たちは内蔵のメカニズムを使うか、自分のものを派生させるか.
いずれにしても面倒ですが、実際にはこのメカニズムを迂回することができ、AuthorizeAttributeも使用できます.
以下はDSOの見方です.
With MVC it is simple to bypass the Membership and Role provider framework altogether. Sometimes it is easier to do this than to implement custom Membership/Role providers, in particular if your authn/authz model doesn't quite fit the mold of those providers.
First, you should realize that you don't need to write everything from scratch, you can use the core Forms authentication API, which can be used independently of the Membership/Role provider framework: FormsAuthentication.SetAuthCookie  - Call this after user has been authenticated, specify the user name Request.IsAuthenticated  - Returns true if SetAuthCookie was called HttpContext.Current.User.Identity.Name  - Returns the user name specified in the call to SetAuthCookie
So here is what you do in MVC to bypass the Membership/Role provider:
Authentication : In your controller, authenticate the user using your custom logic.If successful, call  FormsAuthentication.SetAuthCookie  with the user name.
Authorization : Create a custom authorize attribute (deriving from AuthorizeAttribute) . In the  AuthorizeCore  override, implement your custom authorization logic, taking the user in  HttpContext.Current.User.Identity.Name  and the roles defined in the Roles property of the AuthorizeAttribute base class. Note you can also define properties on your custom authorization attribute and use that in your authorization logic. For example you can define a property representing roles as enumerated values specific to your app, instead of using the Roles property which is just a string.
Affix your controllers and actions with your custom authorize attribute, instead of the default Authorize attribute.
啓発された感じがしましたが、AuthorizeAttributeのAuthorizeCoreをどのように再ロードするかはよくわかりません.そのためにデモを作りました
1.VS 2010を使用してASPを作成する.NET MVC 2 WebエンジニアリングAutは、Modelディレクトリの下にMyAuthAttributeクラスを新規作成し、以下のようにします.
 
view plain copy to clipboard print ?
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
namespace AuthTest.Models  
{  
    public class MyAuthAttribute : AuthorizeAttribute  
    {  
//このメソッドを再ロードするだけで、カスタムロール認可メカニズムをシミュレートします.
        protected override bool AuthorizeCore(HttpContextBase httpContext)  
        {  
            string currentRole = GetRole(httpContext.User.Identity.Name);  
            if(Roles.Contains(currentRole ) )  
                return true;  
            return base.AuthorizeCore(httpContext);  
        }  
  
//ユーザー対応の役割を返します.実際には、SQLデータベースからユーザーの役割情報を読み取ることができます.
        private string GetRole(string name)  
        {  
            switch(name)  
            {  
                case "aaa":  return "User";  
                case "bbb": return "Admin";  
                case "ccc": return "God";  
                default: return "Fool";  
            }  
        }  
    }  
  
}  
 
2.HomeControllerを次のように変更します.
 
view plain copy to clipboard print ?
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using System.Web.Security;  
using AuthTest.Models;  
namespace AuthTest.Controllers  
{  
    [HandleError]  
    public class HomeController : Controller  
    {  
        public ActionResult Index()  
        {  
ViewData["Message"="ASP.NET MVCへようこそ!";  
//シミュレーションユーザー登録成功            FormsAuthentication.SetAuthCookie("aaa", false);  
            return View();  
        }  
  
//カスタムAuthorizeAttributeが機能しているかどうかを確認します.//このアクションは、役割が「God」のユーザーのみがにアクセスできます.
        [MyAuth(Roles="God")]  
        public ActionResult About()  
        {  
            return View();  
        }  
    }  
}  
 
3.F 5を押してデバッグして、ページの上の“について”のリンクをクリックして、ははは、分かりましたか?