如何在Azure Web作业中实例化OWIN IDataProtectionProvider?

Kor*_*ijn 13 azure owin asp.net-identity azure-webjobs

我需要一个IDataProtectionProvider使用UserManagerAzure Web Jobs工作者中的Identity Framework生成电子邮件确认令牌的实例:

var confirmToken = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
Run Code Online (Sandbox Code Playgroud)

这会崩溃,因为null IUserTokenProvider<User, int>被传递给UserManager<User, int>on constru.

在MVC应用程序中,实例创建如下:

public class OWINStartup
{
    public void Configuration(IAppBuilder app)
    {
        var dataProtectionProvider = app.GetDataProtectionProvider();
Run Code Online (Sandbox Code Playgroud)

但是,Azure Web Jobs当然没有OWINStartup钩子.有什么建议?

jst*_*ant 18

看一下OWIN启动上下文Katana源代码,你可以看到它的默认实现是a .不幸的是,这个类没有暴露给我们,只有在azure托管时才能使用.DataProtectionProviderMachineKeyDataProtectionProviderDpapiDataProtectionProvider

你可以在MachineKeyDataProtectionProvider 这里找到实现.您需要,也能实现自己MachineKeyDataProtector所看到这里.这些并不是难以实现的,而且基本上是包装MachineKey.Protect()和包装MachineKey.Unprotect().

为实施MachineKeyDataProtectionProviderMachineKeyDataProtector卡塔纳项目源(Apache 2.0许可):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦实现了它,很容易插入UserManager:

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

希望有助于您找到正确的方向.

  • 这确实有效......有点。但是,由于 `MachineKeyDataProtector` 是在 Web 应用程序之外(在 Web 作业中)使用的,它使用它自己的密钥(不是您可能在 Web 应用程序的 web.config 中指定的任何密钥)。因此,您在此处生成的任何令牌都不会被网络应用程序接受为有效:( 除了滚动不同的 IDataProtector 之外,不确定对此的解决方案...... (3认同)