📜 ⬆️ ⬇️

Getting started with ASP.NET Identity

Many of you should know that the output of ASP.NET MVC 5 was marked by the transition to a new authorization system called ASP.NET Identity. The framework developers strongly recommend switching to a new system, calling its main advantages the possibility of embedding it in absolutely any project (ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR), simple social integration, working on OWIN, installing and updating via NuGet other. Looking closely at the ASP.NET Identity, you can without a twinge of conscience say that this is the next stage in the development of ASP.NET web programming. In this post I will post a simple tutorial to get started with ASP.NET Identity.

After wandering a little bit on the Internet in search of an available tutorial on the implementation of the authorization system in the MVC 5 project, I found a certain number of feature articles, but almost all of them were focused on using the Entity Framework as user data storage. Even the root resource , to my great frustration, could not adequately uncover the topic and answer all the questions of interest.

Suppose we have a MVC project where we would like to use the latest technologies, in particular Owin, Katana and of course ASP.NET Identity. If suddenly the term Owin confuses you, I recommend reading the article .

1. The main libraries that we need: Microsoft.AspNet.Identity.Core, Microsoft.Owin, Microsoft.Owin.Security + everything that depends on and dependent on them. Easy to install with NuGet Package Manager . Through the NuGet console, you can do this:
')
Install-Package Microsoft.AspNet.Identity.Core 


2. Implement the main classes:
 public class ApplicationUser : IUser { public ApplicationUser(string name) { Id = Guid.NewGuid().ToString(); UserName = name; } public string Id { get; private set; } public string UserName { get; set; } } 

Interface Microsoft.AspNet.Identity. IUser requires the implementation of the Id and UserName fields. In addition, you can add the fields you need (Email, Password, City, etc.)

 public class CustomUserStore : IUserStore<ApplicationUser> { static readonly List<ApplicationUser> Users = new List<ApplicationUser>(); public void Dispose() { throw new NotImplementedException(); } public Task CreateAsync(ApplicationUser user) { return Task.Factory.StartNew(() => Users.Add(user)); } public Task UpdateAsync(ApplicationUser user) { throw new NotImplementedException(); } public Task DeleteAsync(ApplicationUser user) { throw new NotImplementedException(); } public Task<ApplicationUser> FindByIdAsync(string userId) { throw new NotImplementedException(); } public Task<ApplicationUser> FindByNameAsync(string userName) { return Task<ApplicationUser>.Factory.StartNew(() => Users.FirstOrDefault(u => u.UserName == userName)); } } 

CustomUserStore , as the name implies, is a user repository and includes basic methods (Create, Update, Delete) for working with them. Here I use the static Users field for storage. Here you can fasten any storage suitable for you. It is also impossible not to pay attention to the type of return value - Task and Task. This means that the methods will be executed asynchronously. There are some good materials on this topic in Habré (for example, here ).

 public class CustomUserManager : UserManager<ApplicationUser> { public CustomUserManager(CustomUserStore store) : base(store) { this.PasswordHasher = new CustomPasswordHasher(); } public override Task<ApplicationUser> FindAsync(string userName, string password) { Task<ApplicationUser> taskInvoke = Task<ApplicationUser>.Factory.StartNew(() => { PasswordVerificationResult result = this.PasswordHasher.VerifyHashedPassword(userName, password); if (result == PasswordVerificationResult.SuccessRehashNeeded) { return Store.FindByNameAsync(userName).Result; } return null; }); return taskInvoke; } } public class CustomPasswordHasher : PasswordHasher { public override string HashPassword(string password) { return base.HashPassword(password); } public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword) { if (true) { return PasswordVerificationResult.SuccessRehashNeeded; } else { return PasswordVerificationResult.Failed; } } } 

CustomUserManager is the main class whose methods we will call to manipulate user data (replacing the old Membership Provider). It must be a successor of Microsoft.AspNet.Identity. UserManager , which contains many virtual methods. In this case, we redefined the FindAsync () method, in which, for example, the password is first checked, and if successful, the user is returned. As you can see, in the UserManeger constructor, we defined our own PasswordHasher, a class designed to manage passwords. The body of the VerifyHashedPassword method has a demo view. You can write your password-checking logic there.

3. Configure the application to work with our CustomUserManager. To do this, in the Startup.cs file that is executed by the Owin assembly when the application is started, add the line:

  app.CreatePerOwinContext(CustomUserManager.Create); 


4. Use CustomUserManager inside the controller:

 public class TestController : ApiController { private static CustomUserManager _customUserManager; public CustomUserManager UserManager { get { return _customUserManager ?? (_customUserManager = HttpContext.Current.GetOwinContext().GetUserManager<CustomUserManager>()); } } public async Task<bool> Authenticate(string name, string password) { if (await UserManager.FindAsync(name, password) != null) { return true; } return false; } } 

You can use those UserManager methods that you have overridden, as well as the standard set of methods of the CustomUserStore class (they are called by default if you use the methods of your UserManager of the same name), which must be defined in a mandatory manner.

5. To use the standard MVC attributes [Authorize], set the type of authorization you need in the Startup class . For example:
 public class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); } } 


List of resources used:
- Simple Asp.net Identity Core Without Entity Framework
- ASP.NET Identity 2.0 Cookie & Token Authentication

PS This material is debut and, of course, does not claim to be an exhaustive manual for ASP.NET Identity. Designed for people familiar with the technology of MVC, who want to get acquainted with the new authorization system.

Source: https://habr.com/ru/post/227351/


All Articles