Forms Authentication 和 OAuth for Web API 项目的混合不会 return 在令牌过期的情况下出现 401

Mix of Forms Authentication and OAuth for Web API project doesn't return 401 in case of expired token

我正在开发 ASP.NET Web API 应用程序,它使用 OAuth (owin) 协议来验证我的客户端。在 API 初始版本发布后的某个时间,我添加了额外的表单身份验证(基于 cookie),并在其之上混合了 ASP.NET MVC 应用程序。现在,在启动过程中我

// forms
app.UseCookieAuthentication(... options ...);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

// oauth
app.UseOAuthAuthorizationServer

它运行完美,我的 MVC 用户可以调用我的 API 而无需进行身份验证,这很酷。唯一的缺点是,它现在会导致很多问题,当我的 API 客户端尝试使用过期令牌而不是 401 错误访问 API 时,我得到 200 和 html 响应我的登录页面。

Request:
GET https://server.com/api/v1/controller/action1
Authoration: bearer <expired token here>

Response:
200 <html>

我需要的是任何带有过期令牌的 API 请求都应该导致 403 http 响应并且没有登录页面。

是否可以在我的混合环境中实现,或者我应该拆分我的解决方案?

CookieAuthenticationProvider 有一个处理程序来自定义此行为

Provider = new CookieAuthenticationProvider()
{
     OnApplyRedirect = ctx =>
     {
         // check if ctx is an API request
         if (!IsApiRequest(ctx))
         {
             ctx.Response.Redirect(ctx.RedirectUri);
         }
     }
}