如何查看传入 API 请求的 TLS 版本 - ASP.NET

问题描述 投票:0回答:1

我有一个托管在 Microsoft Azure 上的 Web 应用程序,其中包含 Web API。我的目标是 .NET Framework 4.5。

我正在完成所有必需的步骤,以使 TLS 1.2 成为传入请求所需的最低版本。

在我正式将传入请求切换到最低 TLS 1.2 之前,我想知道目前是否有人在使用较旧的 TLS 版本,因为我们有第三方使用我们的 API。

有没有办法检测特定 API 请求中协商的 TLS 版本?

例如,我有下面这个API调用。我可以使用 .NET Framework 4.5 编写哪些代码来获取协商的 TLS 版本?

        [HttpGet]
        [Authorize(Roles = "User")]
        public HttpResponseMessage GetFirstName()
        {
            // I would like to add code here to get TLS version negotiated so I can log it

            var email = User.Identity.GetUserName();
            ApplicationUser userFound = GetUserByEmail(email);
            if (userFound == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error: No such user.");
            }
            var firstName = new { FirstName = userFound.FirstName };

            return Request.CreateResponse(HttpStatusCode.OK, firstName);
        }

我知道我最终需要完全升级 .NET Framework,但我需要在 4.5 上找到一个快速解决方案才能解决这个问题。

asp.net azure .net-4.5 tls1.2 webapi
1个回答
0
投票

当然,Panagiotis Kanavos 积分是有效的。升级到受支持的 .NET Framework 版本(例如 4.6.2 或更高版本)可能会有更多帮助。

您可以在 MS doc 中查看,如果您使用的是 4.5v,则需要升级到最新版本。 enter image description here

我尝试过较新版本的.NET Framework 4.6.1。我可以直接从

SslStream
类访问 TLS 版本信息。

using System;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace YourNamespace.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class YourController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> Get()
        {
            LogNegotiatedTLSVersion(Request);

            // Your existing code here

            return "Hello, World!";
        }

        private static void LogNegotiatedTLSVersion(HttpRequest request)
        {
            var certificate = request.HttpContext.Connection.ClientCertificate;
            if (certificate != null)
            {
                using (var sslStream = new System.Net.Security.SslStream(request.HttpContext.Connection.Stream, false))
                {
                    sslStream.AuthenticateAsServer(certificate);
                    var tlsVersion = sslStream.SslProtocol;

                    // Log the negotiated TLS version
                    Console.WriteLine($"Negotiated TLS version: {tlsVersion}");
                }
            }
        }
    }
}
  • SslStream.SslProtocol
    属性用于获取协商的 TLS 版本。调用
    AuthenticateAsServer
    方法来验证连接的服务器端。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.