Introduction to URL-based permission control in ASP. NET MVC

Source: Internet
Author: User

Introduction to URL-based permission control in ASP. NET MVC

Create two tables in the database. The PermissionItem table is used to save the relationship between the permission ID and the page path. A permission ID can have multiple pages. Generally, the page under the same permission ID is used to implement the same function. The PermissionList table is used to save user permissions.

 
 
  1. Code
  2. USE [UrlAuthorize]
  3. GO
  4. /***** Object: Table [dbo]. [PermissionList] Script Date: 07/07/2009 00:07:10 ******/
  5. SET ANSI_NULLS ON
  6. GO
  7. SET QUOTED_IDENTIFIER ON
  8. GO
  9. Create table [dbo]. [PermissionList] (
  10. [ID] [int] IDENTITY (1, 1) not null,
  11. [PermissionID] [int] not null,
  12. [UserID] [int] not null,
  13. CONSTRAINT [PK_PermissionList] PRIMARY KEY CLUSTERED
  14. (
  15. [ID] ASC
  16. ) (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON) ON [PRIMARY]
  17. ) ON [PRIMARY]
  18. GO
  19. SET IDENTITY_INSERT [dbo]. [PermissionList] ON
  20. INSERT [dbo]. [PermissionList] ([ID], [PermissionID], [UserID]) VALUES (1, 2, 1)
  21. INSERT [dbo]. [PermissionList] ([ID], [PermissionID], [UserID]) VALUES (2, 3, 1)
  22. SET IDENTITY_INSERT [dbo]. [PermissionList] OFF
  23. /***** Object: Table [dbo]. [PermissionItem] Script Date: 07/07/2009 00:07:10 ******/
  24. SET ANSI_NULLS ON
  25. GO
  26. SET QUOTED_IDENTIFIER ON
  27. GO
  28. SET ANSI_PADDING ON
  29. GO
  30. Create table [dbo]. [PermissionItem] (
  31. [ID] [int] IDENTITY (1, 1) not null,
  32. [PermissionID] [int] not null,
  33. [Name] [nvarchar] (50) not null,
  34. [Route] [varchar] (100) not null,
  35. CONSTRAINT [PK_PermissionItem] PRIMARY KEY CLUSTERED
  36. (
  37. [ID] ASC
  38. ) (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON) ON [PRIMARY]
  39. ) ON [PRIMARY]
  40. GO
  41. SET ANSI_PADDING OFF
  42. GO
  43. SET IDENTITY_INSERT [dbo]. [PermissionItem] ON
  44. INSERT [dbo]. [PermissionItem] ([ID], [PermissionID], [Name], [Route]) VALUES (1, 1, N 'test page 1 ', n'/Test/Page1 ')
  45. INSERT [dbo]. [PermissionItem] ([ID], [PermissionID], [Name], [Route]) VALUES (2, 2, n' test page 2 ', n'/Test/page2 ')
  46. INSERT [dbo]. [PermissionItem] ([ID], [PermissionID], [Name], [Route]) VALUES (3, 3, N 'test page 3 ', n'/Test/Page3 ')
  47. INSERT [dbo]. [PermissionItem] ([ID], [PermissionID], [Name], [Route]) VALUES (5, 1, N 'test page 4 ', n'/Test/Page4 ')
  48. INSERT [dbo]. [PermissionItem] ([ID], [PermissionID], [Name], [Route]) VALUES (6, 2, n' test page 5 ', n'/Test/page5 ')
  49. SET IDENTITY_INSERT [dbo]. [PermissionItem] OFF

The example in the database indicates that Page1 and Page4 belong to permission 1, Page2 and Page5 belong to permission 2, and Page3 belongs to permission 3. Users with a user ID of 1 have permissions of 2 and 3.

Create an AccountHelper class in the ASP. net mvc Project, which is a helper class. The GetPermissionItems method is used to obtain the correspondence between the permission ID and the page path. This is global, and each user will use this information when accessing the page, so it is stored in the Cache. Database Operations use the ADO. NET Entity Framework.

1/** // <summary>
2 // obtain the permission item
3 /// </summary>
4 /// <returns> permission item list </returns>
5 public static List <PermissionItem> GetPermissionItems ()
6 {
7 // if the permission list information already exists in the cache, it is read directly from the cache.
8 if (HttpContext. Current. Cache ["PermissionItems"] = null)
9 {
10 // if no permission list information exists in the cache, it is obtained from the database and written to the cache.
11 UrlAuthorizeEntities db = new UrlAuthorizeEntities ();
12 var items = db. PermissionItem. Where (c => c. PermissionID> 0). ToList ();
13 HttpContext. Current. Cache ["PermissionItems"] = items;
14}
15
16 // The cache stores the permission IDs of all pages for permission control.
17 return (List <PermissionItem>) HttpContext. Current. Cache ["PermissionItems"];
18}
19

The GetUserPermission method saves the user's permission ID to a one-dimensional Int32 array. This information is different for each user, but is often used, so it is stored in the Session.

1/** // <summary>
2 // obtain User Permissions
3 /// </summary>
4 // <param name = "userID"> User ID </param>
5 /// <returns> User permission array </returns>
6 public static Int32 [] GetUserPermission (int userID)
7 {
8 // if the permission list information already exists in the cache, it is read directly from the cache.
9 if (HttpContext. Current. Session ["Permission"] = null)
10 {
11 // obtain the user permission from the database, put the permission ID in the int array, and store it in the Session
12 UrlAuthorizeEntities db = new UrlAuthorizeEntities ();
13 var permissions = db. PermissionList. Where (c => c. UserID = userID). Select (c => c. PermissionID). ToArray ();
14 HttpContext. Current. Session ["Permission"] = permissions;
15}
16 return (Int32 []) HttpContext. Current. Session ["Permission"];
17}
18

Create a new UrlAuthorizeAttribute class that inherits from AuthorizeAttribute, which is a Filter. We override its OnAuthorization method to execute it in the ASP. NET page lifecycle authentication phase.

1/** // <summary>
2 // rewrite OnAuthorization
3 /// </summary>
4 /// <param name = "filterContext"> </param>
5 public override void OnAuthorization (AuthorizationContext filterContext)
6 {
7 // obtain the permission item list
8 List <PermissionItem> pItems = AccountHelper. GetPermissionItems ();
9
10 // obtain the permission ID corresponding to the current access page. If item is empty, no permission control information is available on the current page and no permission control is required.
11 var item = pItems. FirstOrDefault (c => c. Route = filterContext. HttpContext. Request. Path );
12
13 if (item! = Null)
14 {
15 if (Array. indexOf <Int32> (AccountHelper. getUserPermission (int. parse (filterContext. httpContext. session ["UserID"]. toString (), item. permissionID) =-1)
16 {
17 // prompt that the permission is insufficient. You can also jump to another page
18 filterContext. HttpContext. Response. Write ("You are not authorized to access this page ");
19 filterContext. HttpContext. Response. End ();
20}
21}
22 else
23 {
24 // if the permission item list does not contain the corresponding permission ID of the current page, all users are not allowed to access it. A prompt is displayed, indicating that no access is permitted. * ** Note 1 ***
25 filterContext. HttpContext. Response. Write ("You are not authorized to access this page ");
26 filterContext. HttpContext. Response. End ();
27}
28}
29

At this point, the main work has been completed. Next, we only need to add [UrlAuthorize] before the Action or Controller that requires URL-based permission control. These Actions or all Actions in the Controller will be automatically processed by the UrlAuthorize Filter. If an Action is marked with [UrlAuthorize] and the database does not have the permission ID corresponding to this page, all users will not be able to access this page according to the sample code, if you need to change this setting, you can modify the two lines of code under "NOTE 1" above.

  1. ASP. NET Error Handling Mechanism
  2. ASP. NET multi-attachment upload and attachment editing
  3. Secrets of performance and scalability in ASP. NET
  4. ASP. NET 3.5 chart controls
  5. Describes the four statuses of ASP. NET.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.