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

为.NET 4.8现有ASP.NET MVC应用添加OpenID Connect

为.NET 4.8的ASP.NET MVC 5应用配置Azure AD OpenID Connect SSO

1. 安装必要的NuGet包

直接在NuGet包管理器中安装以下包:

  • Microsoft.Owin.Security.OpenIdConnect(官方OWIN OpenID Connect中间件,替代老旧的DotNetOpenAuth)
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Host.SystemWeb

2. 手动添加OWIN配置类

因为你的项目没有默认生成认证配置文件,需要手动创建:

创建Startup.cs(项目根目录)

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(YourMvcProjectNamespace.Startup))]
namespace YourMvcProjectNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 引入认证配置
            App_Start.StartupAuth.ConfigureAuth(app);
        }
    }
}

创建App_Start/Startup.Auth.cs

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Configuration;
using System.Threading.Tasks;

namespace YourMvcProjectNamespace.App_Start
{
    public static class StartupAuth
    {
        public static void ConfigureAuth(IAppBuilder app)
        {
            // 设置默认的登录认证类型为Cookie
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // 配置Cookie认证,用于存储本地会话
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                LoginPath = new PathString("/Account/Login") // 自定义登录跳转路径,可选
            });

            // 配置OpenID Connect对接Azure AD
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = ConfigurationManager.AppSettings["AzureADClientId"],
                Authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["AzureADTenantId"]}/v2.0",
                RedirectUri = ConfigurationManager.AppSettings["AzureADRedirectUri"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["AzureADPostLogoutRedirectUri"],
                Scope = "openid profile email", // 请求的用户信息范围
                ResponseType = "id_token", // 仅请求ID Token,无需授权码

                // 异常处理逻辑
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
        }
    }
}

3. 配置Web.config参数

在web.config的<appSettings>节点中添加Azure AD相关配置:

<appSettings>
  <!-- 替换为你的Azure AD应用信息 -->
  <add key="AzureADClientId" value="你的应用客户端ID"/>
  <add key="AzureADTenantId" value="你的租户ID(GUID或租户域名)"/>
  <add key="AzureADRedirectUri" value="https://localhost:44300/signin-oidc"/> <!-- 需与Azure AD后台配置的重定向URI完全一致 -->
  <add key="AzureADPostLogoutRedirectUri" value="https://localhost:44300/"/>
</appSettings>

4. 添加登录/注销控制器逻辑

创建或修改AccountController:

using System.Web.Mvc;
using Microsoft.Owin.Security;

public class AccountController : Controller
{
    public void Login()
    {
        if (!Request.IsAuthenticated)
        {
            // 触发Azure AD认证流程
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
        else
        {
            RedirectToAction("Index", "Home");
        }
    }

    public void Logout()
    {
        // 同时注销本地Cookie和Azure AD会话
        HttpContext.GetOwinContext().Authentication.SignOut(
            CookieAuthenticationDefaults.AuthenticationType,
            OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

5. 页面添加登录/注销入口

在布局页(如_Layout.cshtml)中添加链接:

@if (Request.IsAuthenticated)
{
    <span>欢迎, @User.Identity.Name! </span>
    @Html.ActionLink("注销", "Logout", "Account")
}
else
{
    @Html.ActionLink("登录", "Login", "Account")
}

6. Azure AD后台配置

在Azure门户中完成以下操作:

  • 注册一个应用程序,设置支持"Accounts in this organizational directory only"
  • 在"Authentication"菜单中添加重定向URI(即Web.config中配置的AzureADRedirectUri)
  • 记录下应用的客户端ID和租户ID,填入Web.config

注意事项

  • 不要使用DotNetOpenAuth.AspNet,微软官方已推荐使用OWIN系列的OpenID Connect组件,兼容性和后续维护更好
  • 确保NuGet包版本与.NET 4.8兼容,建议选择4.x版本的OWIN相关包
  • 如果项目原有Forms认证,需移除或调整,避免认证逻辑冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:25:34