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

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

 

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

01

  1. 先在登入成功的地方放入一段程式,來把使用者有權限進入的頁面以字串的方式存入Session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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

 

  1. 再來新建一個檔案名為CustomAuthorize.cs,程式碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

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內的字串。

  1. 這樣就可以在Action上面加上標籤來驗證使用者權限囉!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

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