6

I'm in the process of building a web api in visual studio 2013 and want to authenticate using OWIN middleware and bearer tokens. However I already have a database and don't want to use Microsoft's new Identity framework as the majority of tables and columns that it auto generates I simply don't need.

Can anyone point me in the right direction of how to apply this type of authentication without having to use the Microsoft Identity framework?

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
Tron Diggy
  • 95
  • 1
  • 8
  • Here is my answer to this question that I posted on another thread: http://stackoverflow.com/a/31465144/3532945 – brando Jul 19 '15 at 04:11

2 Answers2

2

I prob. dont understand the question entirely but it looks like you are trying to do without the whole owin pipeline?

If not then..

You need to implement few interfaces related to users and roles described as below.

http://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity

Have a look at the following post from Scott Allen

http://odetocode.com/blogs/scott/archive/2013/11/25/asp-net-core-identity.aspx

This way you can use your own tables, DAL and services to create UserManager and RoleManager objects.

Edit: Samples over here should give you some pointers.

Edit2: Custom User Store Example. IRepository is the object which takes care of CRUD.

    public class CustomUserStore : IUserStore<User>,....
    {
        private readonly IRepository _repository;
        public CustomUserStore(IRepository repository)
        {
            if (repository == null)
                throw new ArgumentNullException("repository");
            _repository = repository;
        }
        public Task CreateAsync(User user)
        {
            if (user == null) throw new ArgumentException("user");
            _repository.User.Add(user);
            return _repository.CommitAsync();
        }
...
activebiz
  • 6,000
  • 9
  • 41
  • 64
  • Thanks for your reply I basically want to be able to issue bearer tokens without having to use the ASP.net Identity framework, main issue is not having to use the code first migrations and stick to using my current DAL to perform any checks if that makes sense. – Tron Diggy Aug 12 '14 at 14:34
  • It looks like you dont want to use IdentityFramework's EF implementation as you already have your own Tables and DAL. Well in that case the above two (esp. first) link should do. I personally dont like using the IdentityFramework as it comes with EF which I dont (sort of) have complete control over. So I have implemented those interfaces and use my own tables and DAL. – activebiz Aug 12 '14 at 14:40
  • Yes that's what i'm after as well complete control always wins. When implementing the stores do you have to implement all of them as its a bit over kill for what i'm after. at the moment all i want is if username and password matches an entry in my db then create a bearer token and use it to authorize any future requests to my api. – Tron Diggy Aug 12 '14 at 14:58
  • You only have to implement the stores you want, the UserStore is the only must do. RoleStore sound like it is likely for you. Even with that you only have to actually implement the methods you actually us too. Just walk through your use cases and see which ones the UserManager calls. – Philip Nelson Aug 12 '14 at 15:06
  • Do you know of a end to end example/tutorial for implementing custom storage and using it to produce bearer tokens for a webapi. The example above is just copying the current table structure into a mySQL database where as mine is completely different to what the identity frameworks provide by default – Tron Diggy Aug 12 '14 at 15:29
  • Have a look at https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/CustomMembershipSample/CustomMembershipSample.sln . You might not see many example which has end to end design in place. Might good idea to get your UserManager/RoleManager implemented first and then configure your owin pipeline. – activebiz Aug 12 '14 at 15:36
2

My suggestion would be to use the framework but extend it to use your objects and infrastructure. I am currently in the middle of doing this and landed on this question. Here's how I've tackled it so far:

Step 1: Your own CustomUserObject

Write/Use your own "ApplicationUser" object. In the template project, you want to modify the "IdentityModels" file. It has ApplicationUser object defined in there. Assuming you already have all the properties from your existing app, you will need to add GenerateUserIdentityAsync() method but change the type of the parameter to UserManager manager). After the change, your method signature looks like this:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<CustomUserObject> manager)

Step 2: Define your own IUserStore<> implementation

Add a new class CustomUserStore that implements IUserStore, like so:

public class CustomUserStore : IUserStore<CustomUserObject>
{
    private readonly IUserManagerService _userManagerService;
    public CustomUserStore(IUserManagerService userManagerService)
    {
        _userManagerService = userManagerService
    }

    //implementation code for all of the IUserStore methods here using
    //userManagerService or your existing services/classes
}

I am using Unity to inject IUserManagementService's implementation above.

I have made use of the comprehensive UserManager class that comes with the Microsoft Identity framework but extended the framework to use my API for authentication and authorization. You could write your own UserManager but I found that it is pretty tedious and there is no reason why UserManager could work for most cases of Securing an app.

Step 3: Changes in the IdentityConfig.cs file

Change the class definition to make ApplicationUserManager class inherit from UserManager

You'll need to do the samething in the constructor of this class as well; i.e. have IUserStore. Modify the Create static method's first line to make use of the new store and a wrapper class that provides as a means to be a "DbContext" like so:

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<UserManagementServiceWrapper>()));
        //modify the relevant lines after this to suit your needs
        ...
    }

My UserManagementServiceWrapper looks like this (please note that I'm not too happy that it inherits from a concrete UserManagementService class that provides the methods to connect to the service that provides user data, I'm still building this out):

public class UserManagementServiceWrapper : UserManagementService, IDisposable
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

Step 4: Change the ApplicationDbContext class to return a UserManagementServiceWrapper instance

public class ApplicationDbContext : UserManagementServiceWrapper
{
    public static UserManagementServiceWrapper Create()
    {
        return new UserManagementServiceWrapper();
    }
}

And that is pretty much it. You still have to write the implementation for CustomUserStore object but everything should work.

Please note this is not boilerplate code and no where near "code review ready", as I said, I'm still digging deeper into this and building it out to use custom stores, data access objects, services etc. I thought you'll get a good start with some of the things that took me a couple of hours to figure out. I will blog about this when I have a good solution.

Hope this helps.

amythn04
  • 388
  • 2
  • 11
  • Thanks for your reply how are you handling CRUD operations to your database? Are you using the default Identity framework bindings and code first migrations? as this is something i don't want to use as i already have my own EF built but i'm not sure where to replace my the existing bindings with my own DAL. – Tron Diggy Aug 13 '14 at 08:12
  • If you have interface to the object which takes care of your CRUD operations, then you can pass that interface to the constructor of the CustomUserStore object (Edited the post above). – activebiz Aug 13 '14 at 10:01
  • Yes ok that makes sense. Please can you post a link to your blog when you have created it for other users to reference in conjunction with this post, Thanks again. – Tron Diggy Aug 13 '14 at 10:10
  • Sure, I will. I should have it up by the weekend :) – amythn04 Aug 14 '14 at 17:37