How to use TLS 1.2 in ASP.NET Core 2.0

时间秒杀一切 提交于 2020-11-27 04:04:47

问题


My salesforce res apis were working fine until. When suddenly I started getting authentication errors. retry your request. Salesforce.Common.AuthenticationClient.d__1.MoveNext().

salesforce informed that it would use from now TLS .1.2. How can I enforce my asp.net core 2.0 to use TLS 1.2 in Startup.cs. below is my code for login.

 private async Task<AuthenticationClient> GetValidateAuthentication()
        {
            RestApiSetting data = new RestApiSetting(Configuration);
            var auth = new AuthenticationClient();
            var url = data.IsSandBoxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";
            try
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                await auth.UsernamePasswordAsync(data.ConsumerKey,
                data.ConsumerSecret, data.Username, data.Password, url);
                return auth;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

回答1:


.net framework prior to version 4.7 makes outbound connections using TLS 1.0 by default. You can upgrade to a newer version to fix the problem, or alternatively, you can set the default and fallback versions for outbound calls using the ServicePointManager, or passing the setting into the HttpClient if you have the source code for the library.

Add the following somewhere early in your pipeline, such as your startup.cs or global.asax:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

You can find a good description on the topic here: https://social.msdn.microsoft.com/Forums/en-US/8db54c83-1329-423b-8d55-4dc6a25fe826/how-to-make-a-web-client-app-use-tls-12?forum=csharpgeneral

And if you want to specify it only for some requests instead of application-wide, then you can customize the HttpClientHandler of your HttpClient:

var handler = new HttpClientHandler
{
    SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
};

HttpClient client = new HttpClient(handler);
...



回答2:


According to the following https://github.com/dotnet/corefx/issues/29452

In .NET Core, ServicePointManager affects only HttpWebRequest. It does not affect HttpClient. You should be able to use HttpClientHandler.ServerCertificateValidationCallback to achieve the same.



来源:https://stackoverflow.com/questions/49399205/how-to-use-tls-1-2-in-asp-net-core-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!