[Authorize]
Public ActionResult Index ()
Marking the way, can realize that the marked action must be authenticated users to access;
By using
[Authorize (users= "username")]
The way, can realize the marked action must be a specific user to access, the above two methods are very convenient to use, in the Needdinner sample program has a Hugh implementation process,
However, we use most of the actual application is role-based (Roles) authentication methods, Needdinner is not given, this article gives a concrete implementation (based on the asp.net forms validation) process:
Step 1
Write the authentication cookie to the client after completing username and password Authentication
Code
Copy Code code 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 the cookie when the user logs on to the site
Code
Copy Code code 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
This allows you to use the following effects
Copy Code code as follows:
[Authorize (roles= "admin")]
Public ActionResult Index (int. Page)