如何处理无法访问的 ADFS 元数据

How to handle unreachable ADFS metadata

对于我的 ASP.NET MVC 应用程序,我正在使用 ADFS 身份验证。设置方式如下

            app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                MetadataAddress = ConfigurationManager.AppSettings.Get("MetadataAddress"),
                Wtrealm = ConfigurationManager.AppSettings.Get("Realm"),
            });

由于我无法控制的原因,MetadataAddress 中的元数据有时无法访问。在这种情况下,我想将用户重定向到自定义视图而不是默认错误视图。如何做到这一点?

我最终做的是创建 Owin 中间件,它捕获无效元数据抛出的错误,如下所示,并将用户重定向到描述问题的路由:

public class LoggingMiddleware : OwinMiddleware
{
    public LoggingMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public async override Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        } catch(Exception e)
        {
            Logger.Error($"Encountered error in authenticating {e.ToString()}");
            if(e.Source.Equals("Microsoft.IdentityModel.Protocols"))
            {
                context.Response.Redirect("/Home/OwinError");
            } else
            {
                throw e;
            }
        }
    }
}

只需将中间件添加到 startup.cs 文件中,使用以下行:

app.Use(typeof(LoggingMiddleware));