How can I instantiate OWIN IDataProtectionProvider in Azure Web Jobs?

非 Y 不嫁゛ 提交于 2019-12-20 09:38:03

问题


I need an instance of IDataProtectionProvider to generate email confirmation tokens using the Identity Framework UserManager in an Azure Web Jobs worker:

var confirmToken = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

This crashes because a null IUserTokenProvider<User, int> was passed to the UserManager<User, int> upon constuction.

In the MVC application an instance is created like this:

public class OWINStartup
{
    public void Configuration(IAppBuilder app)
    {
        var dataProtectionProvider = app.GetDataProtectionProvider();

But of course, Azure Web Jobs doesn't have an OWINStartup hook. Any advice?


回答1:


Taking a look at the Katana source code for the OWIN startup context you can see the default implementation of the DataProtectionProvider is a MachineKeyDataProtectionProvider. Unfortunately this class is not exposed to us, only the DpapiDataProtectionProvider which will not work when hosted in azure.

You can find the implementation of the MachineKeyDataProtectionProvider here. You will need to also implement your own MachineKeyDataProtector as seen here. These are not difficult implmentations and are essentially wrappers around MachineKey.Protect() and MachineKey.Unprotect().

The implementation for MachineKeyDataProtectionProvider and MachineKeyDataProtector from the Katana project source (apache 2.0 license):

internal class MachineKeyProtectionProvider : IDataProtectionProvider
{
    public IDataProtector Create(params string[] purposes)
    {
        return new MachineKeyDataProtector(purposes);
    }
}

internal class MachineKeyDataProtector : IDataProtector
{
    private readonly string[] _purposes;

    public MachineKeyDataProtector(string[] purposes)
    {
        _purposes = purposes;
    }

    public byte[] Protect(byte[] userData)
    {
        return MachineKey.Protect(userData, _purposes);
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return MachineKey.Unprotect(protectedData, _purposes);
    }
}

Once you have that implemented it is easy to plug into the UserManager:

var usermanager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
var machineKeyProtectionProvider = new MachineKeyProtectionProvider();
usermanager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(machineKeyProtectionProvider.Create("ASP.NET Identity"));

Hope that helps get you in the right direction.



来源:https://stackoverflow.com/questions/28606676/how-can-i-instantiate-owin-idataprotectionprovider-in-azure-web-jobs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!