How to implement a basic identity authentication in ASP. NET Core, asp. netcore

Source: Internet
Author: User

How to implement a basic identity authentication in ASP. NET Core, asp. netcore

ASP. NET can finally be cross-platform, but it is not a common ASP. NET, but an ASP. NET Core, which can deploy your web applications across Windows, Linux, OS X, and other platforms. You can understand that this framework is ASP. the next version of NET, compared with the traditional ASP.. NET Program, which has some differences. For example, many class libraries are not universal between the two platforms.

Today, we first implement a basic identity authentication in ASP. NET Core, which is a login function.

Preparations:

1. We recommend using VS 2015 Update3 as your IDE,: http://www.bkjia.com/softjc/446184.html

2. You need to install the. NET Core runtime environment and development tools, provided here VS version: http://www.bkjia.com/softs/472362.html

Create a project:

Create a project in VS, select ASP. NET Core Web Application (. NET Core) as the project type, and enter the project name TestBasicAuthor.

Next, select Web Application and No Authentication for identity Authentication on the right.

Open Startup. cs

Add the following code to the ConfigureServices method:

services.AddAuthorization(); 

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,   AutomaticChallenge = true });

The complete code should be as follows:

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 entered code reports an error. This is because the corresponding package has not been introduced. Go to the error line and click the light bulb to load the corresponding package.

Create a folder named "Model" under the project and add a class User. cs to it.

The Code should be 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.UserList     .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);    if (userFromStorage != null)   {     //you can add all of ClaimTypes in this collection     var claims = new List<Claim>()     {       new Claim(ClaimTypes.Name,userFromStorage.UserName)       //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")     };      //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(20),       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"); }

Let's add a class to simulate user storage in the same file.

//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>() {    new User { UserName = "User1",Password = "112233"}  };}

Next, fix 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.microsoft.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 userFromStorage = TestUserStorage.UserList        .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);      if (userFromStorage != null)      {        //you can add all of ClaimTypes in this collection         var claims = new List<Claim>()        {          new Claim(ClaimTypes.Name,userFromStorage.UserName)           //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")         };        //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(20),          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");    }  }  //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>() {    new User { UserName = "User1",Password = "112233"}  };  }}

Create an Account folder in the Views folder and a View file named index. cshtml in the Account folder.

Paste the following code:

@model TestBasicAuthor.Model.User

Open HomeController. cs

Add an Action, AuthPage.

[Authorize][HttpGet]public IActionResult AuthPage(){  return View();}

Add a view named AuthPage. cshtml under Views/Home

At this point, a basic identity authentication is complete. The core login method is as follows:

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties{  ExpiresUtc = DateTime.UtcNow.AddMinutes(20),  IsPersistent = false,  AllowRefresh = false});

The verification is 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  });}

Add [Author] to a Controller or Action to configure the page for logging on to verification.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.