Search code examples
c#asp.netasp.net-identity

Asp.Net Identity connecting to DB via Web Api


I am working on a legacy MVC application which initially had forms authentication via a custom class and implementation. I have modified it and utilised Asp.Net Identity which is working as expected.

My requirement now is that this MVC application no longer should have direct access to the database. So I have removed the connection string from the web.config and have been looking at making all database calls via calls to my web service (Asp.Net Web Api).

I have custom classes for:

  • UserStore
  • RoleStore
  • etc

Please note I have a custom user class as it is a custom user table.

Questions

1) Is the correct way to achieve my goal? It's likely I will be overriding many methods which had previously used the IdentityDBContext such as:

public override Task<CustomUser> FindByIdAsync(int usrID)

public override Task<Customer> FindByNameAsync(string userName)

2) I am finding that

FindByNameAsync()

is working as expected and the user is being passed to the method however FindByIdAsync() is passing userid as 0. Why would FindByIdAsync() not be passing my actual userid?

To call FindByIdAsync() I am implementing a UserStore:

public class CustomUserStore : UserStore
    <
        CustomUser, 
        CustomRole, 
        int,
        CustomUserLogin, 
        CustomUserRole, 
        CustomUserClaim
    >
{

and then overriding FindByIdAsync():

public override Task<CustomUser> FindByIdAsync(int usrID)
    {
        var response = client.GetAsync("api/user/" + usrID).Result.Content;
        return response.ReadAsAsync<CustomUser>(
             new List<MediaTypeFormatter> {
                new XmlMediaTypeFormatter(),
                new JsonMediaTypeFormatter()
            });
        //return base.FindByIdAsync(userId);
    }

The issue is that usrID is 0.


Solution

  • I now have this working, so my mvc application is using AspNet.Identity but for all the database calls it is calling my api. The solution was indeed to implement IUserStore (and other interfaces as required) and there are a lot of answers and guides on the Internet for this. A good starting point is:

    https://learn.microsoft.com/en-us/aspnet/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity