使用OWIN/Katana在Azure上的数据保护操作不成功

Mat*_*rie 19 security cryptography azure owin

我正在尝试在Azure中运行的基于OWIN/Katana的ASP.NET MVC网站上实现密码重置.

它在本地运行时工作正常但在生产中失败.

我创建了一个UserToken提供程序

userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset"))
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试生成令牌时,如下所示

var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
Run Code Online (Sandbox Code Playgroud)

我得到以下例外.

System.Security.Cryptography.CryptographicException:数据保护操作失败.这可能是由于没有为当前线程的用户上下文加载用户配置文件引起的,这可能是线程模拟时的情况.在System.Security.Cryptography.ProtectedData.Protect(字节[]的UserData,字节[] optionalEntropy,DataProtectionScope范围)在System.Security.Cryptography.DpapiDataProtector.ProviderProtect(字节[]的UserData)在System.Security.Cryptography.DataProtector.Protect (字节[]的UserData)在Microsoft.Owin.Security.DataProtection.DpapiDataProtector.Protect(字节[]的UserData)在Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider 2.d__0.MoveNext()---来自先前堆栈跟踪结束位置,其中的例外是在Microsoft.AspNet.Identity.UserManager`2.d__e9.MoveNext抛出---在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(工作任务)在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task) ()

小智 12

当我尝试在Web API中使用ASP .Net标识和自定义登录功能生成令牌时,我遇到了同样的问题.

"数据保护操作不成功.这可能是由于没有为当前线程的用户上下文加载用户配置文件引起的,这可能是线程模拟时的情况."

我所做的只是创建一个WEBSITE_LOAD_USER_PROFILE在Microsoft Azure中调用的应用程序设置,并将其设置为1.该解决方案适用于我.

你可以在这里看到细节

  • 这里最简单的解决方案,就像链接所说,我需要避免应用此设置的BASIC和SHARED计划. (2认同)

Ogg*_*las 6

如果主机服务器是虚拟机,则可能正是错误消息所显示的内容。检查您的IIS中的应用程序池是否真的Load User Profile设置为true,如异常所示:

  • 在“连接”窗格中,展开服务器名称,然后单击“应用程序池”。
  • 右键单击您的池
  • 高级设置

在此处输入图片说明


Lor*_*sen 5

请看我对这个问题的答案.通过利用可以实现更简单的解决方案IAppBuilder.GetDataProtectionProvider()


JLu*_*ada 4

我找到了解决方案。我不确定所有步骤是否都是必需的,但现在我的应用程序运行良好:

1.- 更新您的 web.config 以支持 securityTokenHandlers

<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
Run Code Online (Sandbox Code Playgroud)

在 configSections 节点中。和

  <securityTokenHandlers>
    <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
                System.IdentityModel, Version=4.0.0.0, Culture=neutral,
                PublicKeyToken=B77A5C561934E089" />

    <add
      type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,
          System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral,
          PublicKeyToken=B77A5C561934E089">
      <sessionTokenRequirement lifetime="00:30:00"></sessionTokenRequirement>
    </add>
  </securityTokenHandlers>

</identityConfiguration>
Run Code Online (Sandbox Code Playgroud)

作为常规节点。2.- 在您的 Startup.Auth.cs 文件中,更新您的 ConfigureAuth(IAppBuilder 应用程序),如下所示:

public void ConfigureAuth(IAppBuilder app)
        {

            UserManagerFactory = () =>
            {
                var userManager = new UserManager<SIAgroUser>(new UserStore<UserType>(new SIAgroUserDbContext()));

                IDataProtectionProvider provider = app.GetDataProtectionProvider();

                //userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<UserType>(provider.Create("PasswordReset") );
                if (provider != null)
                {
                    userManager.UserTokenProvider = new DataProtectorTokenProvider<UsertType, string>(provider.Create("PasswordReset"));
                }

                return userManager;
            };

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();



        }
Run Code Online (Sandbox Code Playgroud)

3.- 清理 Startup 类的构造函数,如下所示:

static Startup()
{
   PublicClientId = "self";
}
Run Code Online (Sandbox Code Playgroud)

这对我有用:)我希望它也对你有用