In ASP. net mvc, you can use the built-in
[Authorize]
Public actionresult index ()
Marking method. The marked action can be accessed only by authenticated users;
Use
[Authorize (users = "username")]
To realize that the marked action can be accessed only by a specific user. The preceding two methods are very convenient to use. In the needdinner exampleProgramThere is a rest implementation process in,
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
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
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:
[Authorize (roles = "admin")]
Public actionresult index (Int? Page)
Very convenient!