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

ASP.NET MVC 4.7.2集成Azure AD认证遇OWIN库404错误求助

解决ASP.NET MVC 4.7.2集成Azure AD认证时SignIn出现404错误的方案

以下是针对你遇到的OWIN库返回404 (Not Found)错误的排查和修复步骤:

1. 验证OWIN Startup类配置

  • 确认项目中存在Startup.cs类,且已通过程序集属性指定启动入口:
    [assembly: OwinStartup(typeof(YourAppNamespace.Startup))]
    namespace YourAppNamespace
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
                
                app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigurationManager.AppSettings["ida:ClientId"],
                    Authority = ConfigurationManager.AppSettings["ida:Authority"],
                    RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"],
                    PostLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"],
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
            }
        }
    }
    
  • 确保UseOpenIdConnectAuthentication配置中的Authority格式正确,比如v1.0端点为https://login.microsoftonline.com/{TenantId},v2.0为https://login.microsoftonline.com/{TenantId}/v2.0,需与Azure AD应用注册的端点版本一致。

2. 检查web.config中的Azure AD配置项

  • 确认appSettings中的配置值与Azure AD应用注册信息完全匹配:
    <appSettings>
      <add key="ida:ClientId" value="你的应用客户端ID" />
      <add key="ida:TenantId" value="你的租户ID" />
      <add key="ida:Authority" value="https://login.microsoftonline.com/你的租户ID" />
      <add key="ida:RedirectUri" value="https://localhost:44300/Account/Callback" />
      <add key="ida:PostLogoutRedirectUri" value="https://localhost:44300/" />
    </appSettings>
    
  • 重点核对RedirectUri:必须与Azure AD应用注册中"身份验证"页面配置的重定向URI完全一致,包括协议(HTTP/HTTPS)、端口和路径。

3. 修正AccountController的SignIn方法实现

  • 确保SignIn方法正确触发OWIN认证挑战,而非手动跳转:
    public class AccountController : Controller
    {
        public void SignIn()
        {
            // 触发OpenID Connect认证流程
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }
    
        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut(
                CookieAuthenticationDefaults.AuthenticationType,
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    
        // 回调动作,需与RedirectUri对应
        public async Task<ActionResult> Callback()
        {
            var result = await HttpContext.GetOwinContext().Authentication.AuthenticateAsync(OpenIdConnectAuthenticationDefaults.AuthenticationType);
            // 处理认证结果,比如存储用户信息
            return RedirectToAction("Index", "Home");
        }
    }
    
  • 注意:SignIn方法不应返回View或手动跳转,而是通过Challenge触发OWIN的认证流程。

4. 确认OWIN NuGet包版本兼容性

  • 确保以下NuGet包版本匹配,避免版本冲突:
    • Microsoft.Owin
    • Microsoft.Owin.Security
    • Microsoft.Owin.Security.Cookies
    • Microsoft.Owin.Security.OpenIdConnect
    • Microsoft.Owin.Host.SystemWeb
      建议统一使用4.x系列版本(如4.2.2),与.NET Framework 4.7.2兼容。

5. 检查IIS及应用池配置

  • 应用池需设置为集成模式,经典模式会导致OWIN中间件无法正常处理请求。
  • 确保应用的匿名认证已启用(SignIn页面需要允许匿名访问,否则会触发未授权重定向循环)。

6. 验证路由配置

  • 检查RouteConfig.cs,确保默认路由能正确匹配Account控制器的SignIn动作:
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    
  • 若存在自定义路由,确认未覆盖Account/SignIn的路由规则。

内容的提问来源于stack exchange,提问作者Ragesh Puthiyedath Raju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:01:03