How to realize the processing method of role-based access Control in ASP.NET MVC
This article will explain in detail how to achieve role-based access control in ASP.NET MVC. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
[Authorize]
Public ActionResult Index ()
The marked ACTION must be an authenticated user before it can be accessed.
By using the
[Authorize (Users= "username")]
The marked ACTION can only be accessed by a specific user. The above two methods are very convenient to use, and there is a specific implementation process in the NeedDinner sample program.
However, most of the Roles-based authentication methods we use in practical applications are not given in NeedDinner. This paper gives the specific implementation (based on ASP.NET Forms verification) process:
Step 1
After completing the UserName and Password authentication, write the authentication Cookie to the client
Code
The copy code is as follows:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (
one,
UserName
DateTime.Now
DateTime.Now.AddMinutes (20)
False
"admin" / / write to user roles
);
String encryptedTicket = FormsAuthentication.Encrypt (authTicket)
System.Web.HttpCookie authCookie = new System.Web.HttpCookie (FormsAuthentication.FormsCookieName, encryptedTicket)
System.Web.HttpContext.Current.Response.Cookies.Add (authCookie)
Step 2
Add the following code to the Global.asax.cs file to read the Cookie when the user logs in to the website
Code
The copy code is as follows:
Protected void Application_AuthenticateRequest (Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies [FormsAuthentication.FormsCookieName]
If (authCookie = = null | | authCookie.Value = = "")
{
Return
}
FormsAuthenticationTicket authTicket = null
Try
{
AuthTicket = FormsAuthentication.Decrypt (authCookie.Value)
}
Catch
{
Return
}
String [] roles = authTicket.UserData.Split (new char [] {';'})
If (Context.User! = null)
{
Context.User = new System.Security.Principal.GenericPrincipal (Context.User.Identity, roles)
}
}
Step 3
In this way, you can use to achieve the following effects
The copy code is as follows:
[Authorize (Roles= "admin")]
Public ActionResult Index (int? Page)
This is the end of this article on "how to achieve role-based access control in ASP.NET MVC". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.