You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将ASP.NET Core的SAML认证Startup代码迁移到旧版ASP.NET WebForms

ASP.NET WebForms 适配Azure SAML认证改造方案

前置准备

首先通过NuGet包管理器安装OWIN版本的SAML2扩展包:Sustainsys.Saml2.Owin,这是适配非Core版ASP.NET的SAML2认证组件,你项目中已有的Microsoft.Owin.Security.Cookies相关依赖无需调整。

代码适配说明

ASP.NET WebForms使用OWIN管道认证体系,和ASP.NET Core的IServiceCollection配置逻辑不同,不需要用到services对象,直接通过IAppBuilder的扩展方法配置即可,对应改造后的ConfigureAuth代码如下:

public void ConfigureAuth(IAppBuilder app)
{
    // 原有Cookie认证配置保持不变
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
        AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
        // 生产环境保持CookieSecure为Always
        CookieSecure = CookieSecureOption.Always,
        SlidingExpiration = true,
        ExpireTimeSpan = TimeSpan.FromHours(4) // 优化原有Ticks计算写法,效果一致
    });
    Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;

    // 替换原有WsFederation配置,新增SAML2认证配置,参数和你提供的Core代码一一对应
    app.UseSaml2Authentication(new Saml2AuthenticationOptions(false)
    {
        SPOptions = new SPOptions
        {
            // 对应Core代码中的SPOptions.EntityId,需和Azure AD企业应用中配置的标识符完全一致
            EntityId = new EntityId("https://localhost:44342/Saml2")
        },
        IdentityProviders =
        {
            new IdentityProvider(
                new EntityId("https://sts.windows.net/63eb1bcb-f74f-4703-8243-6f73d78ebf52/"), 
                new SPOptions())
            {
                // 对应Core代码中的IDP元数据地址
                MetadataLocation = "https://login.microsoftonline.com/63eb1bcb-f74f-4703-8243-6f73d78ebf52/federationmetadata/2007-06/federationmetadata.xml?appid=9fd05134-d507-479b-a432-580541125356",
                AllowUnsolicitedAuthnResponse = true
            }
        }
    });

    // 保持默认登录凭证存储类型为Cookie,未登录访问鉴权页面会自动触发SAML2认证挑战
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseStageMarker(PipelineStage.Authenticate);
}

配套配置注意事项

  • 需要在Azure AD企业应用的断言消费服务(ACS) URL配置中,添加你站点的/Saml2/Acs路径,本地测试场景对应为https://localhost:44342/Saml2/Acs,生产环境替换为正式域名即可
  • 如果站点存在不需要登录即可访问的公开页面,需要在web.config中添加配置放开权限:
<configuration>
  <location path="你的公开页面路径">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>
</configuration>
  • 生产环境部署时需要将EntityId替换为你正式站点的对应地址,保证和Azure侧配置一致。

内容的提问来源于stack exchange,提问作者RKh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:09:04