---restore content starts---
ASP. MVC5 Login and user identity management (Basic)
Recently, there are some pages in the website that require privileged access (admin), so we study how to implement user identity management.
Because the project I started with was an empty project, adding folders and core references checked the MVC so there was no login using the authorize feature;
A new project was created and the authentication was selected as an individual user account. The comparison may be due to the lack of startup.auth.cs files.
The following code is the login code I wrote
1 [HttpGet]2 PublicActionResult Login ()3 {4 returnView ();5 }6 [HttpPost]7 [Validateantiforgerytoken]8 Publicactionresult Login (login login)9 {Ten varUsers = db. Users.where (A = A.name = =Login. UserName); One if(!users. Any ()) A returnView (); -User User =users. First (); - varCards = db. Cards.where (A = a.user_id = =user. ID); theCard Card =cards. First (); - if(Login. password=="123"&&card. privilege==2) - { -FormsAuthenticationTicket Ticket =NewFormsAuthenticationTicket ( + 1, - Login. UserName, + DateTime.Now, ADateTime.Now.AddMinutes ( -), at false, - "Admin" - ); - varCookie =NewHttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket)); -Cookies. HttpOnly =true; - HttpContext.Response.Cookies.Add (cookie); in returnRedirecttoaction (".. /database/selectuser"); - } to returnRedirecttoaction ("Login"); + -}
Where FormsAuthenticationTicket is an encrypted ticket for storing the user's information, where "admin" is the user's permission for the authorize (roles= "admin") feature in the controller.
Next is the controller to restrict permissions
1 Public classDatabasecontroller:controller2 {3 4 PrivateAccessControlContext db =NewAccessControlContext ();5 //Users6 Publicactionresult Selectuser ()7 {8 varuser =db. Users;9 returnView (user. ToList ());Ten } One [HttpGet] A[Authorize (Roles ="Admin")] - Publicactionresult Insertuser () - { the returnView (); - } -}
where the [Authorize (roles= "admin"] flag is only available to users with admin privileges. Of course, you can also register Authorizeattribute as a global filter and need to add it to registerglobalfilters (included in the \app_start\filterconfig.cs file)
Public Static void registerglobalfilters (globalfiltercollection filters) { filters. ADD (new Handleerrorattribute ()); Filters. ADD (new System.Web.Mvc.AuthorizeAttribute ()); }
Then decorate with the [allowanonymous] feature in front of methods that require external access.
If user authentication fails, we typically choose to redirect the user to the login interface. To authenticate users who have permission to view the original page.
In previous versions of ASP, this redirect was intercepted by the FormsAuthenticationModule Onleave method and redirected to the landing page defined in the application Web. config file as follows
1 < mode= "Forms">2 <loginurl = "~/account/login" Timeout = "2880" /> 3 </ Authentication >
But in MVC5 we can change the code in the Stratup.auth.cs directly
app. Usecookieauthentication (New cookieauthenticationoptions { AuthenticationType = Defaultauthenticationtypes.applicationcookie, loginpath = new PathString ("/account/login"), Provider = new Cookieauthenticationprovider { //enables the application to verify the security stamp when the user logs on. //This is a security feature that will be used when you change your password or add an external login to your account. onvalidateidentity = securitystampvalidator.onvalidateidentity < Applicationusermanager , ApplicationUser > ( validateInterval:TimeSpan.FromMinutes (), regenerateidentity: (manager, user) = user. Generateuseridentityasync (manager)) } );
The above code loginpath this variable is pointing to our landing page, we can change the back "/account/login" to change the point. Startup.Auth.cs file I'm not quite sure, I should also update the article for this file later.
Then the code that landed the view
1 @model Access_Control_System.Models.Login2 @{3 viewbag.title = "View";4 }5 6 <H2>Login</H2>7 8 @using (Html.BeginForm ())9 {Ten @Html. AntiForgeryToken (); One @Html. ValidationSummary (True, "", new {@class = "Text-danger"}) A <fieldsetclass= "Form-horizontal"> - <Divclass= "Form-group"> - @Html. Labelfor (Model=>model. username,htmlattributes:new {@class = "Control-label col-md-2"}) the <Divclass= "Col-md-10"> - @Html. Editorfor (Model=>model. username,new {htmlattributes=new {@class = "Form-control"}}) - @Html. Validationmessagefor (Model=>model. UserName, "", new {@class = "Text-danger"}) - </Div> + </Div> - <Divclass= "Form-group"> + @Html. Labelfor (Model=>model. Password, htmlattributes:new {@class = "Control-label col-md-2"}) A <Divclass= "Col-md-10"> at @Html. Editorfor (Model=>model. password,new {htmlattributes=new {@class = "Form-control"}}) - @Html. Validationmessagefor (Model=>model. UserName, "", new {@class = "Text-danger"}) - </Div> - </Div> - - in <Divclass= "Form-group"> - <Divclass= "Col-md-offset-2 col-md-10"> to <inputtype= "Submit"value= "Submit"class= "Btn Btn-default" /> + </Div> - </Div> the * </fieldset> $ Panax Notoginseng}
ASP. NET MVC Login Implementation