OwinMiddleware Authentication(ws federation) - MVC5 Identity 2 - IDX10201:SecurityTokenHandlers都无法读取'securityToken'

时间:2015-07-30 12:22:25

标签: asp.net token owin acs ws-federation

我正在尝试向ACS服务器进行身份验证,我确实设法通过配置文件以旧方式使用http模块进行身份验证,但我无法使用它来使用owin。这是我的创业公司的相关部分

        app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType =
                    WsFederationAuthenticationDefaults.AuthenticationType
            });
app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                MetadataAddress =
                    "https://*******.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml",
                Wtrealm = "http://localhost:62569/",
                Wreply = "http://localhost:62569/callback-signin",
                SecurityTokenHandlers = new SecurityTokenHandlerCollection
                {
                    new MachineKeySessionSecurityTokenHandler
                    {
                        Configuration = new SecurityTokenHandlerConfiguration
                        {
                            CertificateValidationMode = X509CertificateValidationMode.None,
                            IssuerNameRegistry = new ValidatingIssuerNameRegistry
                            {
                                IssuingAuthorities =
                                    new List<IssuingAuthority>
                                    {
                                        new IssuingAuthority("https://*******.accesscontrol.windows.net/")
                                        {
                                            Thumbprints = { "9B9F8B5E21640ED692C*****A62B4077813659B5" },
                                            Issuers = { "https://*******.accesscontrol.windows.net/" }
                                        }
                                    }
                            }
                        }
                    }
                }
            });

这是工作配置文件

<?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=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />    
    <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" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=********.database.windows.net,1433;Initial Catalog=*********;Persist Security Info=True;User ID=m*******;Password=*******" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5" />
  </system.web>



  <system.webServer>
    <modules>
      <add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
      <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>


 <system.identityModel>
    <identityConfiguration>
      <audienceUris>
        <add value="http://localhost:62569" />
      </audienceUris>
      <securityTokenHandlers>
        <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </securityTokenHandlers>
      <certificateValidation certificateValidationMode="None" />
      <issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
        <authority name="https://**********.accesscontrol.windows.net/">
          <keys>
            <add thumbprint="9B9F8B5E21640ED692CC1CF2A62B4077813659B5" />
          </keys>
          <validIssuers>
            <add name="https://*********.accesscontrol.windows.net/" />
          </validIssuers>
        </authority>
      </issuerNameRegistry>
    </identityConfiguration>
  </system.identityModel>
  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
      <wsFederation passiveRedirectEnabled="true" issuer="https://***********.accesscontrol.windows.net/v2/wsfederation" realm="http://localhost:62569" reply="http://localhost:62569/callback-signin" requireHttps="false" />
    </federationConfiguration>
  </system.identityModel.services>      

      <entityFramework>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="Data Source=***********.database.windows.net,1433;Initial Catalog=********;Persist Security Info=True;User ID=*************;Password=********" />
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>

    </configuration>

使用Owin我收到此错误:

  

抛出异常:   'System.IdentityModel.Tokens.SecurityTokenValidationException'中   mscorlib.dll中

     

附加信息:IDX10201:没有   SecurityTokenHandlers可以读取'securityToken':

    <?xml version="1.0" encoding="UTF-8"?>
<Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_19fb92df-c8ac-4388-9294-7a8cdb3bcf0b" IssueInstant="2015-07-30T12:07:25.837Z" Version="2.0">
   <Issuer>https://*********.accesscontrol.windows.net/</Issuer>
   <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
         <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
         <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
         <ds:Reference URI="#_19fb92df-c8ac-4388-9294-7a8cdb3bcf0b">
            <ds:Transforms>
               <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
               <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <ds:DigestValue>wEjAPR2kWtfrRKX9tMGvJu/Nv+yLtm1KeXbYFDwbB8U=</ds:DigestValue>
         </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>GVamldoBjB+RZY+2bf2700k2Z4PUtp+7Cy9EGTne5+7ID+tLmQ08yXur898O21ldqVqqmGxKbVYQRPVRkF1F+e3bBRipEhyvZ4K8oxQly6f0lLza2svTBSI8GUhLQ9/5ElReaOAgM84q3V5XcBvmXHamanRFSd5hzkTqWbRlNFWJFisqKEuTBTl2DLNV/CeWKrv+11qTgGc0Qxk18mycDGXDfwuWAYcVAZMImiEFm8wErIfOaQ9EbKYqtoVdbuKb5WH2+yjI6jp7uHRKl6x2z77XVLuNRLbutgQDASMGt2dll4P7Ve/tt/NqzkHj7P/zbkEYckY6r1W2Tv1kUeh6vg==</ds:SignatureValue>
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
         <X509Data>
            <X509Certificate>MIIDSjCCAjagAwIBAgIQrcBhMtovuJ9MilbEjMjS7TAJBgUrDgMCHQUAMDExLzAtBgNVBAMTJm1hcmdvY29uc2VpbC5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE1MDYxNjA4MTYzOFoXDTIwMDUzMTIyMDAwMFowMTEvMC0GA1UEAxMmbWFyZ29jb25zZWlsLmFjY2Vzc2NvbnRyb2wud2luZG93cy5uZXQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpeZseXX1IYTABUOPr7nfIAXc7cXAI0k+vR3qEbvy0UxEhYAkAocQR2qUTPQ8D1v4lPp59tnHKBGJ0eHt9DYm/SyKkfHsWfqsysZx5NHXSJIhy/SgHwpd8b2q1NKxqBRLrdJKyAua+WWza4p/HMFjEVoN/upZtngSqxUKO/oYqy6m7smkz8vwjzpJR8tyqN881XBQzvryiF/i3ZPFQqlCT9263TMcAGPpym9uvxHzFPPx3u8IDz3AQydyHeViaJhiXGic0VEcm6LMn3JLOYqAzJnv8z89NdpsL4ynv1ekytt/8yyza3CnsU1E4tFDj1HU3785aFZ1xm6wr1MUK9VOTAgMBAAGjZjBkMGIGA1UdAQRbMFmAEN1alzwM3lJSHdh4LFl7uxmhMzAxMS8wLQYDVQQDEyZtYXJnb2NvbnNlaWwuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldIIQrcBhMtovuJ9MilbEjMjS7TAJBgUrDgMCHQUAA4IBAQAsQ5jNKvS2fLtqs9oB6DGTXdI5nAli5UyvZUQlnf******ifG14SRbVdTjUOzngIWAJ5KAQk5t//wSkwgAS+U6AFYI/mee9NLEvOEhrRbpGUP0oL504OZ9zTDeXmGu2FybRB2TvdTKLaeVsBvwqgP33QFkcuPK50fCGC1l3SecIeyWL5fsiw/2+GuTKHjCaeRqnYBgDTINptc9PGayLPBTjs4UPzbccmaYyuanmTAMZGU0iRoGJYet2uAasT52QvWZqD0NUZbWyR1N8CBf5EIW2S/TrpoOBYNgZQU5n9PRJjTBhESHXjfa8RipC8RXU9o</X509Certificate>
         </X509Data>
      </KeyInfo>
   </ds:Signature>
   <Subject>
      <NameID>******.*******@********.net</NameID>
      <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer" />
   </Subject>
   <Conditions NotBefore="2015-07-30T12:07:25.837Z" NotOnOrAfter="2015-07-30T13:07:25.837Z">
      <AudienceRestriction>
         <Audience>http://localhost:62569/</Audience>
      </AudienceRestriction>
   </Conditions>
   <AttributeStatement>
      <Attribute Name="http://schemas.microsoft.com/identity/claims/tenantid">
         <AttributeValue>7102feaa-34af-4756-85ce-b0f69766d78d</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name">
         <AttributeValue>*****.*******@*******.net</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname">
         <AttributeValue>******</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname">
         <AttributeValue>*******</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.microsoft.com/identity/claims/identityprovider">
         <AttributeValue>https://sts.windows.net/7102feaa-34af-4756-85ce-b0f69766d78d/</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider">
         <AttributeValue>https://sts.windows.net/7102feaa-34af-4756-85ce-b0f69766d78d/</AttributeValue>
      </Attribute>
   </AttributeStatement>
   <AuthnStatement AuthnInstant="2015-07-27T12:39:30.003Z">
      <AuthnContext>
         <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
      </AuthnContext>
   </AuthnStatement>
</Assertion>

我在那里失踪了什么?任何可以帮助我的事情都非常受欢迎我已经在这方面苦苦挣扎了好几天!

1 个答案:

答案 0 :(得分:1)

当您为WS-Federation middlware指定SecurityTokenHandlers属性时,您将为其提供安全令牌处理程序的权威列表,它应该用于验证它接收的任何安全令牌,从而阻止创建默认令牌处理程序。

通过指定MachineKeySessionSecurityTokenHandler实例,中间件只能验证SessionSecurityToken个实例。这种类型的令牌用于传递会话数据。您无法在从Azure AD收到的邮件中看到此令牌,因此中间件邮件是准确的:它无法读取安全令牌。

经过身份验证的会话的管理由cookie中间件处理 - 它将发出&#34;登录&#34;一旦您使用外部身份验证登录,就会生成cookie。除非您使用多个身份验证Cookie,否则您不需要指定AuthenticationType值。

相反,您需要使用SignInAsAuthenticationType选项告诉WS-Federation中间件使用cookie身份验证中间件执行登录。这意味着在验证来自Azure AD租户的登录消息后,它将触发cookie身份验证中间件以向响应添加cookie。然后,该cookie将用于后续请求,以使用Azure AD中的标识登录用户。

配置如下所示:

app.UseCookieAuthentication(
    new CookieAuthenticationOptions());

app.UseWsFederationAuthentication(
    new WsFederationAuthenticationOptions
    {
        SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
        MetadataAddress = "https://*******.accesscontrol.windows.net/"
             + "FederationMetadata/2007-06/FederationMetadata.xml",
        Wtrealm = "http://localhost:62569/",
        Wreply = "http://localhost:62569/callback-signin"
    });

由于您已指定元数据地址,因此中间件通常能够检索验证Azure AD租户返回的令牌所需的所有信息。不幸的是,这似乎是使用已弃用的Azure Access Control系统,因此您需要自己配置这些令牌的验证。

您可以使用TokenValidationParameters选项以不妨碍创建默认令牌处理程序的方式设置相同的信息。

TokenValidationParameters = new TokenValidationParameters
{
    ValidIssuer = "https://*******.accesscontrol.windows.net/",
    SigningToken = new X509SecurityToken(...)
}