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

如何将Azure AD B2C集成至.NET Framework 4.8遗留应用?

.NET Framework 4.8 集成Azure AD B2C 实操技巧

核心实现步骤

  • 依赖包安装:通过NuGet安装OWIN相关认证包,包括Microsoft.Owin.Security.OpenIdConnect、Microsoft.Owin.Security.Cookies、Microsoft.Owin.Host.SystemWeb,这些包是.NET Framework 4.8对接Azure AD B2C的核心依赖。
  • OWIN启动类配置:在项目中创建OWIN启动类,配置Azure AD B2C的认证参数,示例代码如下:
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

[assembly: OwinStartup(typeof(YourApp.Startup))]
namespace YourApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = "你的Azure AD B2C客户端ID",
                    Authority = "https://你的租户名.b2clogin.com/你的租户名.onmicrosoft.com/B2C_1_你的登录注册策略名",
                    RedirectUri = "应用回调地址(需在Azure门户配置一致)",
                    PostLogoutRedirectUri = "登出后跳转地址",
                    Scope = "openid profile",
                    ResponseType = "id_token",
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        NameClaimType = "name"
                    }
                });
        }
    }
}
  • Web.config参数管理:将敏感参数移至Web.config的appSettings节点,避免硬编码:
<appSettings>
  <add key="ida:ClientId" value="你的客户端ID" />
  <add key="ida:TenantName" value="你的租户名.onmicrosoft.com" />
  <add key="ida:SignUpSignInPolicy" value="B2C_1_SignUpSignIn" />
  <add key="ida:RedirectUri" value="https://localhost:44316/" />
</appSettings>
  • 业务逻辑集成:在需要保护的控制器或Action上添加[Authorize]特性,触发认证流程;同时添加登录、登出的处理方法:
public ActionResult Login()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties { RedirectUri = "/" },
            OpenIdConnectAuthenticationDefaults.AuthenticationType);
        return new HttpUnauthorizedResult();
    }
    return RedirectToAction("Index", "Home");
}

public ActionResult Logout()
{
    HttpContext.GetOwinContext().Authentication.SignOut(
        CookieAuthenticationDefaults.AuthenticationType,
        OpenIdConnectAuthenticationDefaults.AuthenticationType);
    return RedirectToAction("Index", "Home");
}
  • Azure门户配置验证:确保Azure AD B2C门户中,客户端应用的回调地址与代码配置一致,且所用的注册/登录策略已发布生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:20:57