使用企业代理后面的 ASPNET Core 2 通过 Azure AD 进行身份验证

Authenticate with Azure AD using ASPNET Core 2 from behind Corporate Proxy

我有一个 ASPNET Core 2 应用程序,我正在尝试使用 OpenId 对 Azure AD 进行身份验证。我只有在 ASPNET Core 2 模板中选择单一组织身份验证的样板代码,因此没有自定义代码。我关注了这篇文章here.

由于代理,该应用无法从 Azure AD 应用程序获取元数据。如果我只是将其粘贴到浏览器中,则相同的 URL returns 数据。

我得到的错误是:

HttpRequestException: Response status code does not indicate success: 407 (Proxy Authentication Required).

System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() IOException: IDX10804: Unable to retrieve document from: 'https://login.microsoftonline.com/my-tenant-id/.well-known/openid-configuration'.

Microsoft.IdentityModel.Protocols.HttpDocumentRetriever+d__8.MoveNext()

我有另一个 ASPNET 4.5.2 应用程序,在如下代码中设置代理后,我可以使用与上面相同的 Azure AD 应用程序执行身份验证:

System.Net.HttpWebRequest.DefaultWebProxy = new WebProxy
        {
            Address = new Uri("http://my-company-proxy:8080"),
            Credentials = new NetworkCredential
            {
                UserName = "proxyusername",
                Password = "proxypassword"
            }
        };

所以基本上我的问题是通过 ASPNET Core 2 中的代理身份验证。

我试过 Microsoft.AspNetCore.Proxy 包。它几乎坏了,对我不起作用。我还尝试在 machine.config 中添加代理条目(实际上 4.5.2 应用程序不需要),但效果不佳。我相信通过公司代理应该是非常微不足道的,但到目前为止看起来并不像。

In Full .net framework setting up a proxy is using a config setting entry but to use an HTTP proxy in .net core ,you have to implement IWebProxy interface.

Microsoft.AspNetCore.Proxy 是代理中间件,它服务于不同的目的(设置反向代理)而不是作为 http 代理。请参阅此 article 了解更多详细信息

要在 .net core 中实现 webproxy,

public class MyHttpProxy : IWebProxy
    {

        public MyHttpProxy()
        {
           //here you can load it from your custom config settings 
            this.ProxyUri = new Uri(proxyUri);
        }

        public Uri ProxyUri { get; set; }

        public ICredentials Credentials { get; set; }

        public Uri GetProxy(Uri destination)
        {
            return this.ProxyUri;
        }

        public bool IsBypassed(Uri host)
        {
            //you can proxy all requests or implement bypass urls based on config settings
            return false; 

        }
    }


var config = new HttpClientHandler
{
    UseProxy = true,
    Proxy = new MyHttpProxy()
};

//then you can simply pass the config to HttpClient
var http = new HttpClient(config)

结帐https://msdn.microsoft.com/en-us/library/system.net.iwebproxy(v=vs.100).aspx

Tracher 的评论为我指明了正确的方向,我让它工作了,但为了帮助大家,下面是你需要做的:

  builder.AddOpenIdConnect(options => options.BackchannelHttpHandler = new HttpClientHandler
        {
            UseProxy = true,
            Proxy = new WebProxy
            {
                Credentials = new NetworkCredential
                {
                    UserName = "myusername",
                    Password = "mypassword"
                },
                Address = new Uri("http://url:port")
            }
        });