[Authorize]
Public ActionResult Index ()
Marking method. The marked ACTION can be accessed only by authenticated users;
Use
[Authorize (Users = "username")]
Can realize that the marked ACTION can be accessed only by a specific user. The above two methods are very convenient to use, and there is a closed implementation process in the NeedDinner sample program,
However, most of the methods we use in practical applications are role-based authentication, but not in NeedDinner. This article provides the specific implementation (Based on ASP. NET Forms authentication) process:
Step 1
After UserName and Password authentication, write the authentication Cookie to the client.
Code
Copy codeThe Code is as follows:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (
1,
UserName,
DateTime. Now,
DateTime. Now. AddMinutes (20 ),
False,
"Admin" // write user role
);
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 cookies when users log on to the website.
Code
Copy codeThe 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, the following effects can be achieved:
Copy codeThe Code is as follows:
[Authorize (Roles = "admin")]
Public ActionResult Index (int? Page)