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

OpenID Connect回调URI返回404错误的技术求助

ASP.NET 4.8 + OWIN OpenID Connect回调URI返回404,中间件未处理请求

使用OpenID Connect完成认证后,浏览器访问回调URI(如https://localhost:44368/signin-oidc)时返回404错误,该请求似乎被当作静态文件处理。

项目是Visual Studio 2022中创建的ASP.NET 4.8基础项目,必须使用OWIN中间件实现从登录页重定向到主页的OpenID Connect认证,但OWIN中间件完全忽略了回调请求。

已尝试的排查步骤

  • 更换不同的回调名称,确保与项目静态文件无冲突
  • 多次核对Azure AD、Web.config及认证配置中的URI路径完全匹配
  • 使用Fiddler检查Microsoft返回的POST请求,确认包含code和state参数

补充信息

添加了AuthorizationCodeReceived、MessageReceived、RedirectToIdentityProvider和SecurityTokenReceived四个基础通知处理器,目前六个处理器中仅AuthorizationCodeReceived、MessageReceived、RedirectToIdentityProvider被触发,SecurityTokenValidated和AuthenticationFailed等未触发。

Web.config代码

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="signin-oidc">
    <system.webServer>
      <handlers>
        <clear />
        <add name="OwinCallbackHandler"
             path="signin-oidc" 
             verb="*" 
             type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb" 
             resourceType="Unspecified" 
             preCondition="integratedMode,runtimeVersionv4.0" />
      </handlers>
    </system.webServer>
  </location>
  <appSettings>
    <add key="ClientId" value="(redacted)" />
    <add key="ClientSecret" value="(redacted)" />
    <add key="Authority" value="https://login.microsoftonline.com/(redacted)/v2.0" />
    <add key="RedirectUri" value="https://localhost:44368/signin-oidc" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

添加处理器前的Startup.cs代码

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

[assembly: OwinStartup(typeof(OpenID_Test.Startup))]
namespace OpenID_Test
{
  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      app.Use(async (context, next) =>
      {
        // 该行输出会多次出现在输出窗口
        System.Diagnostics.Debug.WriteLine("Incoming request: " + context.Request.Method + " " + context.Request.Path + " Query: " + context.Request.QueryString);
        await next();
        System.Diagnostics.Debug.WriteLine("After first next(), status code: " + context.Response.StatusCode);
      });
      app.UseErrorPage(new ErrorPageOptions()
      {
        ShowCookies = true,
        ShowEnvironment = true,
        ShowQuery = true,
        ShowExceptionDetails = true,
        ShowHeaders = true,
        ShowSourceCode = true,
        SourceCodeLineCount = 10
      });

      System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
      app.SetDefaultSignInAsAuthenticationType(
        CookieAuthenticationDefaults.AuthenticationType);
      app.UseCookieAuthentication(new CookieAuthenticationOptions());
      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
      {
        ClientId = ConfigurationManager.AppSettings["ClientId"],
        ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
        Authority = ConfigurationManager.AppSettings["Authority"],
        RedirectUri = ConfigurationManager.AppSettings["RedirectUri"],
        CallbackPath = new PathString("/signin-oidc"),
        ResponseType = "code",
        Scope = "openid profile email",
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
          SecurityTokenValidated = context =>
          {
            // 该行输出不会出现在输出窗口
            System.Diagnostics.Debug.WriteLine("\n\nSecurityTokenValidated triggered\n\n");
            context.AuthenticationTicket.Properties.RedirectUri = "/Home.aspx";
            return Task.FromResult(0);
          },
          AuthenticationFailed = context =>
          {
            // 该行输出也不会出现在输出窗口
            System.Diagnostics.Debug.WriteLine("\n\nAuthenticationFailed triggered\n\n");
            return Task.FromResult(0);
          }
        }
      });
      app.Use(async (context, next) =>
      {
        // 该行输出也会多次出现在输出窗口
        System.Diagnostics.Debug.WriteLine("End of flow before next(): " + context.Request.Method + " " + context.Request.Path + " Query: " + context.Request.QueryString);
        await next();
        System.Diagnostics.Debug.WriteLine("End of flow after next(), status code: " + context.Response.StatusCode);
      });
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:44:49