MVC 5 Custom UserStore

2019-01-18 03:04发布

I need to build a custom UserStore (basically because I have some requirements that are not part of the framework by default) but I can not find any documentation anywhere on how to do this.

I have seen two pieces of information that are close:

  1. http://kazimanzurrashid.com/posts/implementing-user-confirmation-and-password-reset-with-one-asp-dot-net-identity-pain-or-pleasure - Which appears to apply to the earlier edition :(
  2. and MVC 5 IoC and Authentication - Which is similar to what I require but I need to see some code :(

Basically I need to know how to create a user and how to sign in. The rest I can figure out. I guess the main issue is handling passwords, etc.

Does anyone know of any documentation anywhere that might help me? Or if there is a breakdown on the default UserStore and it's internal methods that would be great (I could adapt from there).

1条回答
Bombasti
2楼-- · 2019-01-18 03:42

This is actually not that hard.

Create a new class that implements the IUserStore interface.

public class MyUserStore : IUserStore<User> { }

...then implement its methods. I think there are 5 or 6 to start off with, that deal with creating / updating / deleting / finding users. If you are using entity framework for your user entities, then just constructor inject an instance of it into your user store instance.

public class MyUserStore : IUserStore<User>
{
    private readonly MyDbContext _dbContext;
    public MyUserStore(MyDbContext dbContext) { _dbContext = dbContext; }
}

Then, in the interface methods, just delegate to your dbcontext:

Task IUserStore<User>.CreateAsync(User user)
{
    _dbContext.Set<User>().Create(user);
    return Task.FromResult(0);
}

There are then a lot of other optional interfaces you can implement to support additional features. For example, if you want your UserStore to be able to handle password encryption for you, implement IUserPasswordStore:

public class MyUserStore : IUserStore<User>, IUserPasswordStore<User> { }

... and so on for the other interfaces like IUserRoleStore, etc.

What might really help is a decompilation tool like .NET Reflector or ReSharper's Navigate To Decompiled Sources feature. If you decompile the default UserStore in the Microsoft.AspNet.Identity.EntityFramework library, you can sort of see how they did it. Some of the decompiled code can be hard to read because some of the methods are async, but you should get the gist of it.

查看更多
登录 后发表回答