如何在FederatedAuthenticationModule - C#中发送SAML 2.0请求?

时间:2017-07-28 18:40:41

标签: c# asp.net saml wif ws-federation

我的任务是为自定义应用程序实现SAML。我不明白如何在FederatedAuthenticationModule中发送SAML请求。我知道我已接近完成任务但我不知道如何通知IdP它是我要求的SAML令牌或我想要包含在返回令牌中的信息?我的cs文件中有以下代码:

using System;
using System.IdentityModel.Selectors;
using System.IdentityModel.Services;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Web;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // sam is configured in web.config
            var sam = FederatedAuthentication.SessionAuthenticationModule;

            // fam is not
            var fam = new WSFederationAuthenticationModule();
            fam.FederationConfiguration = FederatedAuthentication.FederationConfiguration;

            var request = new HttpContextWrapper(this.Context).Request;

            // is this the response from the STS
            if (!fam.IsSignInResponse(request))
            {
                // no

                // the STS
                fam.Issuer = "https://sts.midway.edu/adfs/ls";
                // the return address
                fam.Realm = this.Request.Url.AbsoluteUri;

                var req =  fam.CreateSignInRequest(string.Empty, null, false); //fam.RedirectToIdentityProvider();                                    //CreateSignInRequest(string.Empty, null, false);

                // go to STS
                Response.Redirect(req.WriteQueryString());
            }
            else
            {
                // yes

                // get the SAML token
                var securityToken = fam.GetSecurityToken(request);

                var config = new SecurityTokenHandlerConfiguration
                {
                    CertificateValidator = X509CertificateValidator.None,
                    IssuerNameRegistry = new CustomIssuerNameRegistry()
                };
                config.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

                var tokenHandler = new SamlSecurityTokenHandler
                {
                    CertificateValidator = X509CertificateValidator.None,
                    Configuration = config
                };

                // validate the token and get the ClaimsIdentity out of it
                var identity = tokenHandler.ValidateToken(securityToken);

                var principal = new ClaimsPrincipal(identity);

                var token = sam.CreateSessionSecurityToken(principal, string.Empty,
                      DateTime.Now.ToUniversalTime(), DateTime.Now.AddMinutes(20).ToUniversalTime(), false);

                sam.WriteSessionTokenToCookie(token);

                this.Response.Redirect(this.Request.QueryString["ReturnUrl"]);
            }
        }
        public class CustomIssuerNameRegistry : IssuerNameRegistry
        {
            public override string GetIssuerName(SecurityToken securityToken)
            {
                X509SecurityToken x509Token = securityToken as X509SecurityToken;

                return x509Token.Certificate.Subject;
            }
        }
    }
}

我在web.config中有以下内容:

<?xml version="1.0"?>
<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=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20170724040507.mdf;Initial Catalog=aspnet-WebApplication2-20170724040507;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <authentication mode="None"/>
    <!--<compilation debug="true" targetFramework="4.5.2">
      <assemblies>
        <add assembly="AAAAAAAAAA, Version=4.0.0.0, 
          Culture=neutral, PublicKeyToken=xxxxxxxxxx" />
      </assemblies>
    </compilation>-->
    <httpRuntime targetFramework="4.5.2"/>
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization"/>
        <add namespace="Microsoft.AspNet.Identity"/>
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
      </controls>
    </pages>
    <membership>
      <providers>
        <clear/>
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
      </providers>
    </profile>
    <roleManager>
      <providers>
        <clear/>
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/>
      </providers>
    </sessionState>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
    <compilation debug="true"/>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
      <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.identitymodel.services" preCondition="managedHandler"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <remove name="svc-Integrated-4.0"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
  <system.identityModel>
  </system.identityModel>
  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
      <wsFederation issuer="http://xxxxxxxxxxxx""
                      realm="http://localhost:53520/"
                      homeRealm="http://xxxxxxxxx"
                      reply="http://localhost:53520/"
                      passiveRedirectEnabled="true"
                      policy="https://xxxxxxxxx"
                      resource="http://localhost:53520/"
                      requireHttps="false" />
    </federationConfiguration>
  </system.identityModel.services>
</configuration>

0 个答案:

没有答案