c# - 加密异常 : The data is invalid in MVC 4 with WIF enabled

标签 c# security .net-4.0 wif windows-identity

我已经创建了一个 MVC 4 项目并为 Azure ACS 进行了设置。它与 System.Identity 一起工作。我将其更改为使用 Microsoft.Identity 来启用 WIF,我的配置文件现在如下所示:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="microsoft.identityModel"
             type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </configSections>
  <connectionStrings>

    <add name="DefaultConnection"  />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:FederationMetadataLocation" value="https://traffictheory.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml" />
    <add key="ida:ProviderSelection" value="ACS" />
  </appSettings>
  <location path="FederationMetadata">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.web>
    <!--<authorization>
      <deny users="?" />
    </authorization>-->
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.0" />
    <!--Commented out by Identity and Access VS Package-->
    <!--<authentication mode="Forms"><forms loginUrl="~/Account/Login" timeout="2880" /></authentication>-->
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <httpRuntime requestValidationMode="4.5" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
        <add name="WSFederationAuthenticationModule"
       type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <add name="SessionAuthenticationModule"
           type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <add name="ClaimsAuthorizationModule"
           type="Microsoft.IdentityModel.Web.ClaimsAuthorizationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
  <microsoft.identityModel>
    <service>
      <audienceUris>
        <add value="http://localhost:48451/" />
      </audienceUris>

    <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <trustedIssuers>
        <add thumbprint="033F53598E4ED92E51C07238E36BBFF4E67ABAD2" name="https://traffictheory.accesscontrol.windows.net/" />
      </trustedIssuers>
    </issuerNameRegistry>

    <federatedAuthentication>
      <cookieHandler requireSsl="false" />
      <wsFederation passiveRedirectEnabled="true"
                    issuer="https://traffictheory.accesscontrol.windows.net/v2/wsfederation"
                    realm="http://localhost:48451/" reply="http://localhost:48451/"
                    requireHttps="false" />
    </federatedAuthentication>
      <certificateValidation certificateValidationMode="None" />
      </service>
  </microsoft.identityModel>

</configuration>

我的问题是当我运行我得到的网站时:

[CryptographicException: The data is invalid.
]
   System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +318
   Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded) +203

[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
   Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded) +319
   Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +217
   Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +1951
   Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +149
   Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +598
   Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +120
   Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +113
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

最佳答案

WIF 中的默认保护是使用 DPAPI,如果尚未加载配置文件,它将失败(通常在云托管中失败)。您可以使用依赖于 ASP.NET 机器 key 的 MachineKey 保护

http://leastprivilege.com/2012/07/12/machinekey-based-session-protection-for-wif/

另一方面,如果您使用的是 NET 4.5 和内置的 System.IdentityModel。您不再需要 WIF,并且机器 key 保护已在核心组件中可用。此外,您还必须引用 System.IdentityModel.Services dll(其中包含 http 模块)

关于c# - 加密异常 : The data is invalid in MVC 4 with WIF enabled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12553712/

相关文章:

c# - web.config 键值对可以用作 asp.net c# 中的编译时间常量吗?

C#哈希密码创建盐问题

c# - 如何使用 DataContractJsonSerializer 序列化包含日期和时间属性的 JSON 字符串?

c# - Visual Studio 与 EXE 文件中的 DLL 加载时间不同

multithreading - 如何确保线程之间唯一的本地状态以进行电子邮件队列处理

c# - native 文件打开/保存对话框(没有 Windows 窗体或 WPF)

c# - 从*新* ComboBox 文本更新,而不是旧文本

c# - ASP.net core 2.0 MVC 每个新的数据库迁移都包含以前迁移的数据

php - 使用 Codeigniter 在 MySQL 中安全地转义动态表名

session - 安全 cookie 和混合 https/http 站点使用