Asp.NetMVCカスタム権限

10371 ワード

MVCフレームワークの重要な利点は、拡張性が高いことです.権限の管理はWebアプリケーションごとに非常に重要です.マイクロソフトはメンバーシップのデフォルト権限設定を提供していますが、より多くの場合、メンバーシップのデフォルト権限設定は実際のニーズを満たすことはできません.
以下では、簡単な方法で権限をカスタマイズします.
MVCフレームワークでは、コントローラへのアクセスを制限するために属性が一般的に使用される.まず、AuthorizeAttributeクラスからカスタム権限クラスを継承します.
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace MvcApplication_AuthorizeAttribute.Models
 8 {
 9     public class MyAuthAttribute : AuthorizeAttribute  
10     {
11         //
12         protected override bool AuthorizeCore(HttpContextBase httpContext)
13         {
14             if (!httpContext.User.Identity.IsAuthenticated)//          
15                 return false;
16             string[] StrRoles = Roles.Split(',');//                
17             if (string.IsNullOrWhiteSpace(Roles))//
18                 return true;
19             bool isAccess = JudgeAuthorize(httpContext.User.Identity.Name, StrRoles);
20             if (StrRoles.Length > 0 && isAccess) //
21                 return false;
22 
23             return true;
24         }
25         /// <summary>
26         ///                  
27         /// </summary>
28         /// <param name="UserName"></param>
29         /// <param name="StrRoles"></param>
30         /// <returns></returns>
31         private bool JudgeAuthorize(string UserName, string[] StrRoles)
32         {
33             string UserAuth = GetRole(UserName);  //            
34             return StrRoles.Contains(UserAuth,    //               
35                              StringComparer.OrdinalIgnoreCase);  //     
36         }
37 
38    
39 
40         //          ,     ,    SQL               
41         private string GetRole(string name)
42         {
43             switch (name)
44             {
45                 case "aaa": return "User";
46                 case "bbb": return "Admin";
47                 case "ccc": return "God";
48                 default: return "Fool";
49             }
50         }  
51     }
52 }

以上のコードは例にすぎません.実際の権限制御ロジックをカスタム権限制御クラス(MyAuthAttribute)に書くことができます.特定のビジネス・プロセスでユーザーにアクセス権がない場合はfalseを返します.次に、このクラスのプロパティを制御するコントローラまたはActionの上に配置します.コードは以下の通りです.
1      [MyAuth(Roles = "User")] 
2         public ActionResult About()
3         {
4             return View();
5         }

これにより、簡単なカスタム権限が完了します.
本明細書のサンプル・コード
リファレンスリンク