首页 > 解决方案 > OWIN 自托管客户端证书认证 403

问题描述

我目前构建了一个简单的 Web API,并正在尝试使用证书实现客户端身份验证。我没有使用 IIS 或其他任何东西作为代理,而只是应用程序本身和 OWIN。我一直在关注本教程,目前包含我试图用来进行身份验证的中间件的代码,并且我已使用将证书绑定到正确的端口

netsh http add sslcert ipport=0.0.0.0:6010 certhash=[removed] appid=[removed] clientcertnegotiation=enable

端口 6010 是我的 API 当前正在侦听的正确端口。

身份验证中间件

public class CertificateAuthenticationMiddleware: OwinMiddleware  
{  
    conststring OwinCertFunc = "ssl.LoadClientCertAsync";  
    conststring OwinCert = "ssl.ClientCertificate";  
    conststring OwinCertError = "ssl.ClientCertificateErrors";  
    public CertificateAuthenticationMiddleware(OwinMiddleware next): base(next)  
    {}  
  
        ///<summary>  
        /// The Invoke() method is invocked from startup class of OWIN for security.  
        ///</summary>  
        ///<param name="context"></param>  
        ///<returns></returns>  
  
    public async override Task Invoke(IOwinContext context)  
    {  
        if (context.Environment.Keys.Contains(OwinCertFunc))  
        {  
            try  
            {  
                var task = (context.Environment[OwinCertFunc] as Func<Task>);  
                awaitTask.Run(task);  
                if (context.Environment.Keys.Contains(OwinCert))  
                {  
                    var cert = context.Environment[OwinCert] asX509Certificate;  
                    if (cert != null) context.Request.Environment.Add(SystemContants.OwinMannatechClientInfo, cert.Subject);  
                    else  
                    {  
                        context.Response.StatusCode = 403;  
                        return;  
                    }  
                }  
                else  
                {  
                    context.Response.StatusCode = 403;  
                    return;  
                }  
                // Exception certError;  
                if (context.Environment.Keys.Contains(OwinCertError))  
                {  
                    //certError = context.Environment[OwinCertError] as Exception;  
                    context.Response.StatusCode = 403;  
                    return;  
                }  
            }  
            catch (Exception ex)  
            {  
                context.Response.StatusCode = 403;  
                return;  
            }  
        }  
        else  
        {  
            context.Response.StatusCode = 403;  
            return;  
        }  
        await Next.Invoke(context);  
    }  
}  

目前,我收到了 403 Forbidden 的响应,这没有任何意义,因为我从客户端传递了正确的证书。

标签: authenticationowin

解决方案


意识到我的中间件顺序错误。记住顺序很重要!


推荐阅读