Thursday, May 8, 2014

Hacky In Memory User Store for ASP.NET Identity 2.0

There are cases when you want to build out a sample ASP.NET Web project (MVC in this case) just to test something out.  I personally hate the defaults that come with most .net mvc projects.  It forces you to create a database, initialize that database, and other useless steps.  Furthermore, I hate working from the predefined templates that come with MVC.  I like that you can get a working app quickly, but it really doesn't help you understand exactly what is going on.

In previous versions of MVC, you would just create a custom membership provider, override a few methods, register it in the web.config and you were off.  Identity 2.0 changed all of that.

In this post I will try and outline what steps I took to create an in memory user store with very limited functionality.  Bear in mind the goal of this article is to get you going in the right direction, and is probably not a complete solution.

The first thing you are going to want to do is read a couple of MS articles to get a good base line.

Adding Identity 2.0 to an empty project
Overview of Custom Storage Providers for ASP.NET Identity

There are a couple of key components here.  The first in managers.  There are built in managers, which are easy enough to use.  The problem is that there is no source code released for the Microsoft.AspNet.Identity, so it is hard to see exactly what the built in user manager does.  It obviously has to interface with the authorization/authentication framework in MVC, but little detail on that has been released.

The second component is the "stores".  Instead of having one big store (or two as in MVC4) they have broken up the stores into various interfaces.  Each store adds a certain amount of functionality to the user store.  It is understood that the manager knows what type of "store" it has received and which interfaces are implemented.  Based on these interfaces, different methods are called and different functionality is available.

The first step in this process is to create an user object.  At a minimum, this user object must implement IUser which only requires a string id and string password.


    public class IdentityUser : IUser
    {
        public IdentityUser(string id, string userName, string hashedPassword)
        {
            Id = id;
            UserName = userName;
            this.hashedPassword = hashedPassword;
        }

        public IdentityUser(string userName)
        {
            UserName = userName;
        }

        public string Id { get; private set; }
        public string UserName { get; set; }
        public string hashedPassword { get; set; }
    }

In the implementation above, I am adding hashedPassword to the object.  You can add any fields you like.  This is probably a hack and probably not the right place to add it, but I am just trying to get something up quickly.

After the user object is created, you need to create a store.  Depending on the features you want to implement, you will implement different interfaces.  See the links above for more.


    public class InMemoryUserStore : IUserStore<identityuser>, IUserPasswordStore<identityuser>
    {
        private IList<identityuser> userList = new List<identityuser>();

        public InMemoryUserStore()
        {
            userList.Add(new IdentityUser("1", "admin", Crypto.HashPassword("admin")));
        }

        public void Dispose()
        {
            
        }

        public Task CreateAsync(IdentityUser user)
        {
            throw new NotImplementedException();
        }

        public Task UpdateAsync(IdentityUser user)
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync(IdentityUser user)
        {
            throw new NotImplementedException();
        }

        public Task<identityuser> FindByIdAsync(string userId)
        {
            return Task.FromResult(userList.FirstOrDefault(x => x.Id.Equals(userId)));
        }

        public Task<identityuser> FindByNameAsync(string userName)
        {
            return Task.FromResult(userList.FirstOrDefault(x => x.UserName.Equals(userName)));
        }

        public Task SetPasswordHashAsync(IdentityUser user, string passwordHash)
        {
            throw new NotImplementedException();
        }

        public Task<string> GetPasswordHashAsync(IdentityUser user)
        {
            return Task.FromResult(userList.First(x => x.UserName.Equals(user.UserName)).hashedPassword);
        }

        public Task<bool> HasPasswordAsync(IdentityUser user)
        {
            var appUser = userList.FirstOrDefault(x => x.UserName.Equals(user.UserName));
            if (appUser == null)
            {
                return Task.FromResult(false);
            }

            return Task.FromResult(!String.IsNullOrEmpty(appUser.hashedPassword));
        }
    }

As you can see from above, I only implemented a few of the methods.  I'm not worried about registration, or edit functionality.  I just need to create an account to login with that plugs in with the built in authentication and authorization frameworks.  As you can see from above, I initialize the user in the constructor. 

After this is done, you can just initialize the user manager and pass it the store that you have created.


    [Authorize]
    public class BaseController: Controller
    {
        public BaseController() : this(new UserManager<identityuser>(new InMemoryUserStore()))
        {
            
        }

        private BaseController(UserManager<identityuser> userManager)
        {
            UserManager = userManager;
        }

        public UserManager<identityuser> UserManager { get; private set; }

        protected IAuthenticationManager AuthenticationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }
 
    }

After this, you have to actually log the user in using the OWIN providers.  You can see samples of this on the internet or if you create a MVC app template with authentication enabled.

Hope that helps!

26 comments:

  1. I am interested in types write-up. It really is good for uncover individuals explain in words about the heart along with knowing in this substantial style is generally merely found. online store Melbourne

    ReplyDelete
  2. It is especially decent, though look into the tips during this home address. software retail

    ReplyDelete
  3. Your article has piqued a lot of positive interest. I can see why since you have done such a good job of making it interesting.WordPress Themes

    ReplyDelete
  4. A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. order cbd online

    ReplyDelete
  5. Thank you very much for this useful article. I like it. cbd oil vape

    ReplyDelete
  6. Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. cbd shop near me

    ReplyDelete
  7. Great post, you have pointed out some excellent points, I as well believe this is a very superb website. best cbd gummies for sale justcbd

    ReplyDelete
  8. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information. cbd retailers

    ReplyDelete
  9. nice bLog! its interesting. thank you for sharing.... wholesale cbd gummies

    ReplyDelete
  10. I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. dotcom secrets

    ReplyDelete
  11. What makes one of these super stores so unmistakable is its size. Immense in size with a parking garage that appears to range on towards forever and passageways of items that never end, the size initially pulls in many.https://open4u.co.uk/33171-asda-superstore-telford-drive-slough-berkshire-slough.html

    ReplyDelete
  12. Thank you very much for this great post. 성인

    ReplyDelete
  13. This group will naturally embrace the new training they will soon receive, and will demonstrate to others in your company the results that can be achieved with the right development. Salesforce interview questions

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Everything has its value. Thanks for sharing this informative information with us. GOOD works! http://www.mamafamille.ca/

    ReplyDelete
  16. Wonderful blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it. Fait a la Main

    ReplyDelete
  17. There are a number of folks that suppose that they're now no longer alcoholics simply due to the fact they have got the cappotential to eat massive quantities of alcohol with out dropping manipulate in their senses, however withinside the proper feel of the word, those human beings also are alcohol based.Local AA Meetings

    ReplyDelete
  18. Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your rss feed to stay informed of any updates. website

    ReplyDelete
  19. There you can download for free, see the first of these data. visit this site

    ReplyDelete
  20. Any animal can take a gander at the WiFi Password Hacker Online segment in the graph and might want to utilize it free of charge. Wifi Hacking Online

    ReplyDelete
  21. Mega Downloader APK gives client controlled scrambled distributed storage space and talk from one side to another ordinary internet browsers, mutually with dedicated applications for portable methodology. Mega Downloader For Pc

    ReplyDelete



  22. Hello, Having my day brightened by the news that the work I produced was superb is very much appreciated.
    https://crackguru.net/ace-utilities-crack-download/

    ReplyDelete