[C#][ASP.NET MVC5] 繼承 AuthorizeAttribute 來實作自訂驗證

有時候會需要頁面會需要依照使用者權限的不同,可以進入的頁面也不同,在MVC裡面有預設Role與User的方式來篩選使用者,不過有時候權限分細一點時就沒辦法應付了,這個時候就需要自訂驗證了。

 

權限表單的結構資料如下:

01

  1. 先在登入成功的地方放入一段程式,來把使用者有權限進入的頁面以字串的方式存入Session
    using (var db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    
    {
    	String account = HttpContext.User.Identity.Name.ToString();
    	var list = db.Query<int>(@"
    SELECT 
    [a].[List_Id]
    FROM [dbo].[Permissions] AS [a]
    WHERE [a].[User_Id] = 
    (	SELECT [Id]
    FROm [dbo].[AspNetUsers] AS [z]
    WHERE [z].Email = @Email)", new { Email = model.Email }).ToList<int>();
    
    	Session["Permissions"] = string.Join(",", list.ToArray());
    }

     

  2. 再來新建一個檔案名為CustomAuthorize.cs,程式碼如下:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace WebApplication_CustomVerification.Verification
    {
        public class CustomAuthorize : AuthorizeAttribute
        {
            public int ListId { get; set; }
    
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                if (httpContext == null)
                {
                    throw new ArgumentNullException("httpContext");
                }
    
                //判斷是否已驗證
                if (httpContext.User.Identity.IsAuthenticated == false)
                {
                    return false;
                }
    
                bool boolIsRight = false;
    
                //Session過期,要求重新登入
                HttpSessionStateBase session = httpContext.Session;
                if (session.Count != 0 &&
                    session["Permissions"] != null &&
                    session["Permissions"].ToString() != "")
                {
                    List<string> list = session["Permissions"].ToString().Split(',').ToList();
                    foreach (var item in list)
                    {
                        if (item == ListId.ToString())
                        {
                            boolIsRight = true;
                            break;
                        }
                    }
                }
    
                return boolIsRight;
            }
        }
    }

    這邊覆寫了原本驗證的機制,改成判斷先前存入Session內的字串。

  3. 這樣就可以在Action上面加上標籤來驗證使用者權限囉!
    using System.Web.Mvc;
    using WebApplication_CustomVerification.Verification;
    
    namespace WebApplication_CustomVerification.Controllers
    {
        public class HomeController : Controller
        {
    
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            [CustomAuthorize(ListId = 1111)]
            public ActionResult List_01()
            {
    
                return View();
            }
    
            [CustomAuthorize(ListId = 1112)]
            public ActionResult List_02()
            {
    
                return View();
            }
    
            [CustomAuthorize(ListId = 1113)]
            public ActionResult List_03()
            {
    
                return View();
            }
        }
    }

 

 

範例程式:https://github.com/shuangrain/WebApplication_CustomVerification

參考:[C#][ASP.NET MVC]自訂AuthorizeAttribute



這裡的資訊對您有用嗎?歡迎斗內給我