Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement login authentication and logout administrator in the development of ASP.NETMVC5 website

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to achieve login authentication and logout administrator in the development of ASP.NET MVC5 website, the content of the article is of high quality, so the editor shares it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

First, business logic layer 1, the implementation of 256 hash encryption method.

Ninesky.Core [right]-> add-> folder, and enter the folder name General.

General folder [right]-> add-> class, enter the class name Security.

Reference the System.Security.Cryptography namespace (1) and implement the SHA256 static encryption method.

2. Administrator model class

Ninesky.Core [right]-> add-> class, and enter the class name Administrator.

Add class code that references System.ComponentModel.DataAnnotations; completion

Using System;using System.ComponentModel.DataAnnotations;namespace Ninesky.Core {/ Manager Model / public class Administrator {[Key] public int AdministratorID {get; set } / account / / [Required (ErrorMessage = "must be entered {0}")] [StringLength (30, MinimumLength = 4, ErrorMessage = "{0} length {2}-{1} characters")] [Display (Name = "account")] public string Accounts {get; set } / password / [DataType (DataType.Password)] [Required (ErrorMessage = "must be entered {0}")] [StringLength (256 heroine ErrorMessage = "{0} characters less than {1} characters")] [Display (Name = "password")] public string Password {get; set;} / login IP / [Display (Name = "login IP")] public string LoginIP {get Set;} / login time / [Display (Name = "login time")] public Nullable LoginTime {get; set;} / creation time / [Display (Name = "creation time")] public DateTime CreateTime {get; set;}

3. Data context

Open Ninesky.Core- > NineskyContext.cs to add Administrators attribute

The content is added in the red box.

4. AdministratorManager management class

Ninesky.Core [right]-> add-> class, and enter the class name AdministratorManager.

Class inherits from BaseManager.

Add a Ninesky.Core.Types reference to the class.

Using Ninesky.Core.Types;using System;namespace Ninesky.Core {public class AdministratorManager: BaseManager {/ add / public override Response Add (Administrator admin) {Response _ resp = new Response (); if (HasAccounts (admin.Accounts)) {_ resp.Code = 0; _ resp.Message = "account already exists";} else _ resp = base.Add (admin); return _ resp Change password / Primary key / New password [ciphertext] / public Response ChangePassword (int administratorID, string password) {Response _ resp = new Response (); var _ admin = Find (administratorID); if (_ admin = = null) {_ resp.Code = 0; _ resp.Message = "the administrator of this primary key does not exist";} else {_ admin.Password = password _ resp = Update (_ admin);} return _ resp;} / delete / Primary key / public override Response Delete (int administratorID) {Response _ resp = new Response (); if (Count () = = 1) {_ resp.Code = 0; _ resp.Message = "unique administrator account cannot be deleted";} else _ resp = base.Delete (administratorID); return _ resp } / find / public Administrator Find (string accounts) {return base.Repository.Find (a = > a.Accounts = = accounts); whether / account / public bool HasAccounts (string accounts) {return base.Repository.IsContains (a = > a.Accounts.ToUpper () = = accounts.ToUpper ()) Update login information / primary key / / IP address / time / public Response UpadateLoginInfo (int administratorID, string ip, DateTime time) {Response _ resp = new Response (); var _ admin = Find (administratorID); if (_ admin = = null) {_ resp.Code = 0; _ resp.Message = "the administrator for this primary key does not exist" } else {_ admin.LoginIP = ip; _ admin.LoginTime = time; _ resp = Update (_ admin);} return _ resp;} / verify / account / / password [ciphertext] / Code:1- successful; 2-account does not exist; 3-password error public Response Verify (string accounts, string password) {Response _ resp = new Response () Var _ admin = base.Repository.Find (a = > a.Accounts = = accounts); if (_ admin = = null) {_ resp.Code = 2; _ resp.Message = "the administrator with account number: [" + accounts + "] does not exist";} else if (_ admin.Password = = password) {_ resp.Code = 1; _ resp.Message = "verified";} else {_ resp.Code = 3; _ resp.Message = "account password error" } return _ resp;}

Second, the realization of the presentation layer

First, add css.

Ninesky.Web- > Content [right]-> add-> sample table, enter the name StyleControl.

Open Ninesky.Web- > App_Start- > BundleConfig.cs.

Add the code in the red box. The details of StyleControl.css are omitted here.

Second, add a reference to Ninesky.Core.

Ninesky.Web- > reference [right]-> add reference. Select Project-> solution-> Ninesky.Core in the reference Manager.

After dealing with these two items, we will continue with the details:

1. Administrator authentication class AdminAuthorizeAttribute

AdminAuthorizeAttribute inherits from AuthorizeAttribute, overrides the AuthorizeCore method, determines whether the administrator has logged in through Session ["AdminID"], and overrides the HandleUnauthorizedRequest method to handle page jumps when not logged in.

Using System.Web;using System.Web.Mvc;namespace Ninesky.Web.Areas.Control {/ administrator authentication class / public class AdminAuthorizeAttribute: AuthorizeAttribute {/ override custom authorization check / protected override bool AuthorizeCore (HttpContextBase httpContext) {if (httpContext.Session ["AdminID"] = = null) return false; else return true } / rewrite unauthorized HTTP request processing / protected override void HandleUnauthorizedRequest (AuthorizationContext filterContext) {filterContext.Result = new RedirectResult ("~ / Control/Admin/Login");}

Ninesky.Web- > Areas- > Control [right]-> add-> class, enter the controller name HomeController.

Add [AdminAuthorize] to HomeController

2. Administrator Controller Ninesky.Web- > Areas- > Control- > Controllers [right]-> add-> Controller. Select MVC5 Controller-null, enter the controller name Admin.

Reference the Ninesky.Core, Ninesky.Core.General, and Ninesky.Web.Areas.Control.Models namespaces in the controller.

Add a private variable private AdministratorManager adminManager = new AdministratorManager ()

Add [AdminAuthorize] to AdminController

3.1 Administrator login

3.1.1 logging in to the View Model

Ninesky.Web- > Areas- > Control- > Models [right]-> add-> class, and enter the class name LoginViewModel.

Namespace Ninesky.Web.Areas.Control.Models {/ public class LoginViewModel {/ account / [Required (ErrorMessage = "must enter {0}")] [StringLength (30, MinimumLength = 4, ErrorMessage = "{2}-{1} characters")] [Display (Name = "account")] public string Accounts {get; set } / password / [DataType (DataType.Password)] [Required (ErrorMessage = "must enter {0}")] [StringLength (20 min length = 6, ErrorMessage = "{0} length {2}-{1} characters")] [Display (Name = "password")] public string Password {get; set;}

3.1.2 Login method

Add the Login () method to AdminController

/ / log in / [AllowAnonymous] public ActionResult Login () {return View ();}

3.1.3 Log in View

Click [right]-> add View on the Login () method

The template selects Create, the model class selects LoginViewModel, and the option selects the reference script library. Code after completion

@ model Ninesky.Web.Areas.Control.Models.LoginViewModel@ {Layout = null Login @ Styles.Render ("~ / Content/controlcss") @ Scripts.Render ("~ / bundles/modernizr") @ Scripts.Render ("~ / bundles/jquery") @ Scripts.Render ("~ / bundles/jqueryval") login @ using (Html.BeginForm ()) {@ Html.AntiForgeryToken () @ Html.ValidationSummary (true, ", new {@ class =" text-danger "}) @ Html.EditorFor (model = > model.Accounts) New {htmlAttributes = new {@ class = "form-control", placeholder = "account"}) @ Html.ValidationMessageFor (model = > model.Accounts, "", new {@ class = "text-danger"}) @ Html.EditorFor (model = > model.Password, new {htmlAttributes = new {@ class = "form-control", placeholder = "password"}) @ Html.ValidationMessageFor (model = > model.Password, "" New {@ class = "text-danger"})}

Add login handling method public ActionResult Login (LoginViewModel loginViewModel) to AdminController

[AllowAnonymous] [ValidateAntiForgeryToken] [HttpPost] public ActionResult Login (LoginViewModel loginViewModel) {if (ModelState.IsValid) {string _ passowrd = Security.SHA256 (loginViewModel.Password); var _ response = adminManager.Verify (loginViewModel.Accounts, _ passowrd); if (_ response.Code = = 1) {var _ admin = adminManager.Find (loginViewModel.Accounts); Session.Add ("AdminID", _ admin.AdministratorID); Session.Add ("Accounts", _ admin.Accounts); _ admin.LoginTime = DateTime.Now _ admin.LoginIP = Request.UserHostAddress; adminManager.Update (_ admin); return RedirectToAction ("Index", "Home");} else if (_ response.Code = = 2) ModelState.AddModelError ("Accounts", _ response.Message); else if (_ response.Code = = 3) ModelState.AddModelError ("Password", _ response.Message); else ModelState.AddModelError ("", _ response.Message);} return View (loginViewModel);}

4. Log out

Add the logout handling method public ActionResult Logout () to AdminController

/ logout / public ActionResult Logout () {Session.Clear (); return RedirectToAction ("Login");}

When it's finished, you can test it by F5.

Login interface, enter the account number mzwhj password 123456, login is successful.

Log in to the successful interface.

On the ASP.NET MVC5 website development on how to achieve login authentication and logout administrator to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report