Note: The code example mentioned in this article > How to achieve a basic authorization in ASP.
How to implement a basic identity authentication in ASP.
Asp. NET can finally cross the platform, but not our usual ASP. But instead of a new platform called ASP., he can deploy your Web application across Windows, Linux, OS X and other platforms, and you can understand that This framework is the next version of ASP, and there are some different places than the traditional ASP, such as many libraries that are not common among the two platforms.
Today we first implement a basic identity authentication with the login function in ASP.
Pre-Preparation:
1. Recommend using VS Update3 as your ide,:www.visualstudio.com
2. You need to install the. NET Core runtime environment and development tools, which are available in VS version: Www.microsoft.com/net/core
To create a project:
To create a new project in VS, the project type is ASP. NET Core WEB Application, enter the project name Testbasicauthor.
Next select Web application, right Authentication selection: No authentication
Open Startup.cs
Add the following code to the Configureservices method:
Add the following code to the Configure method:
App. Usecookieauthentication (new Cookieauthenticationoptions { authenticationscheme = "Cookie", Loginpath = new PathString ("/account/login"), Accessdeniedpath = new PathString ("/account/forbidden"), Automaticauthenticate = True,
The complete code should look like this:
public void Configureservices (iservicecollection services) { services. Addmvc (); Services. Addauthorization (); } public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { app. Usecookieauthentication (New cookieauthenticationoptions { authenticationscheme = "Cookie", Loginpath = New PathString ("/account/login"), Accessdeniedpath = new PathString ("/account/forbidden"), Automaticauthenticate = True, Automaticchallenge = True }); App. USEMVC (routes = { routes. MapRoute ( name: "Default", Template: "{controller=home}/{action=index}/{id}"); });
You may find that the code posted in is an error, this is because the corresponding package has not been introduced into the error line, click the light bulb, load the corresponding package on it.
Create a folder under the project named model and add a class to it User.cs
The code should look like this
public class user{Public string UserName {get; set;} public string Password {get; set;}}
Create a controller named: AccountController.cs
Paste the following code into the class:
[HttpGet] public iactionresult Login () {return View ();} [HttpPost] public async task<iactionresult> Login (User userfromfore) {var userfromstorage = Testuserstorage.use RList. FirstOrDefault (m = m.username = = Userfromfore.username && M.password = = Userfromfore.password); if (userfromstorage! = null) {//you can add all of the claimtypes in this collection var claims = new Lis T<claim> () {new Claim (claimtypes.name,userfromstorage.username)//,new Claim (CLAIMT Ypes. Email, "[email protected]")}; Init the identity instances var userprincipal = new ClaimsPrincipal (new Claimsidentity (claims, "Supersecurelogin ")); Signin await HttpContext.Authentication.SignInAsync ("Cookie", Userprincipal, New authenticationproperties {EXPIRESUTC = DateTime.UtcNow.AddMinutes (), ispersistent = false, Allowrefresh = False }); Return redirecttoaction ("Index", "Home"); } else {viewbag.errmsg = "UserName or Password is invalid"; return View (); }} public Async task<iactionresult> Logout () {await HttpContext.Authentication.SignOutAsync ("Cookie"); Return redirecttoaction ("Index", "Home"); }
In the same file let's add a class that emulates the user store
For simple, I am not using the database to store the user data, just using a static class to replace It.public static CLA SS testuserstorage{Public static list<user> userlist {get; set;} = new list<user> () { new User {Us Ername = "User1", Password = "112233"} };
Next fix the various reference errors.
The complete code should be like this
Using system;using system.collections.generic;using system.linq;using system.threading.tasks;using Microsoft.aspnetcore.mvc;using testbasicauthor.model;using system.security.claims;using microsoft.aspnetcore.http.authentication;//for more information on enabling MVC for empty projects, visit HTTP://GO.MICR osoft.com/fwlink/? Linkid=397860namespace testbasicauthor.controllers{public class Accountcontroller:controller {[HttpGet] Public Iactionresult Login () {return View (); } [HttpPost] public async task<iactionresult> Login (User userfromfore) {var Userfro Mstorage = Testuserstorage.userlist. FirstOrDefault (m = m.username = = Userfromfore.username && M.password = = Userfromfore.password); if (userfromstorage! = null) {//you can add all of the claimtypes in this collection var claims = new List<claim> () { New Claim (Claimtypes.name,userfromstorage.username)//,new Claim (Claimtypes.email, "[EMA Il protected] ")}; Init the identity instances var userprincipal = new ClaimsPrincipal (new Claimsidentity (claims, "supersec Urelogin ")); Signin await HttpContext.Authentication.SignInAsync ("Cookie", Userprincipal, New Authenticationpropertie s {expiresutc = DateTime.UtcNow.AddMinutes (), ispersistent = False , Allowrefresh = false}); Return redirecttoaction ("Index", "Home"); } else {viewbag.errmsg = "UserName or Password is invalid"; return View (); }} public Async task<iactionresult> Logout () {await HttpContext.Authentication.Sig Noutasync ("Cookie"); Return Redirecttoaction ("Index", "Home"); }}//for simple, I-m not using the database to store the user data, just using a static class to replace it. public static class Testuserstorage {public static list<user> userlist {get; set;} = new LIST<USER&G t; () {new User {UserName = "User1", Password = "112233"}}; }}
Create an account folder in the Views folder and create a Fame index.cshtml view file in the Account folder.
Paste in the following code:
@model testbasicauthor.model.user
Open HomeController.cs
Add an action, authpage.
[Authorize] [Httpget]public iactionresult Authpage () { return View ();}
Add a view under Views/home, named Authpage.cshtml
To this, a basic identity authentication is completed, the core landing method is as follows:
Await HttpContext.Authentication.SignInAsync ("Cookie", Userprincipal, new authenticationproperties{ EXPIRESUTC = DateTime.UtcNow.AddMinutes (), ispersistent = False, Allowrefresh = false});
Enable validation as follows:
public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { app. Usecookieauthentication (New cookieauthenticationoptions { authenticationscheme = "Cookie", Loginpath = New PathString ("/account/login"), Accessdeniedpath = new PathString ("/account/forbidden"), Automaticauthenticate = True, Automaticchallenge = True });}
To add [Author] to a controller or action, you can configure a page that requires login verification.
Finally: How do I run this sample and download the full code please visit: How toachieve a basic authorization in ASP .
How to implement a basic identity authentication in ASP.