Как разрешить SSLPeerUnverifiedException: имя хоста не проверено в HttpsURLConnection в приложении NET.MAUI для Android?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как разрешить SSLPeerUnverifiedException: имя хоста не проверено в HttpsURLConnection в приложении NET.MAUI для Android?

Сообщение Anonymous »

Мое приложение NET.MAUI для Android выдает исключение SSLPeerUnverifiedException: имя хоста 192.168.100.2 не проверено при отправке запроса POST на PHP-скрипт, расположенный на локальном хосте IIS моего рабочего стола, как показано ниже.

Код: Выделить всё

await Task.Run(() =>
{
URL urlWebhook = new URL("https://192.168.100.2:443/medservices/ReceiveWebhooks.php");
HttpsURLConnection? connection = urlWebhook.OpenConnection() as HttpsURLConnection;
if(connection != null)
{
connection.DoInput = true;
connection.DoOutput = true;
connection.RequestMethod = "POST";
connection.ConnectTimeout = 10000;
connection.ReadTimeout = 10000;
connection.SetRequestProperty("Content-Type", "application/json");
connection.SetRequestProperty("Accept", "*/*");
connection.SetRequestProperty("User-Agent", "SmsGateway/1.0");
BufferedOutputStream os = new BufferedOutputStream(connection.OutputStream);
os.Write(Encoding.Default.GetBytes(strRequestBody));
os.Close();
isSent = connection.ResponseCode == HttpStatus.Ok;
connection.Disconnect();
}
});
Чтобы настроить привязку https и SSL в IIS, я использовал следующий сценарий PowerShell, который также экспортирует сертификат SSL в форматы pfx и pem.

Код: Выделить всё

$cert_params =
@{
Type = "Custom"
DnsName = "localhost", "192.168.100.2"
FriendlyName = "IIS Express SSL Server Authentication Certificate"
CertStoreLocation = "Cert:\LocalMachine\My"
NotAfter = (Get-Date).AddYears(10)
KeyAlgorithm = "RSA"
KeyLength = 2048
KeyUsageProperty = "All"
KeyUsage = "KeyEncipherment", "DataEncipherment", "DigitalSignature"
KeyExportPolicy = "Exportable"
HashAlgorithm = "SHA256"
TextExtension = @("2.5.29.37={text}1.3.6.1.5.5.7.3.1")
}
$cert = New-SelfSignedCertificate @cert_params
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::Root, [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
$export_params =
@{
Cert = $cert
FilePath = "C:\Users\pnfst\Documents\IISExpress\iis_ssl_server_certificate.pfx"
ChainOption = "EndEntityCertOnly"
Password = ConvertTo-SecureString -String "Kurort@75" -Force -AsPlainText
}
Export-PfxCertificate @export_params
$certBase64 = [System.Convert]::ToBase64String($cert.RawData, [System.Base64FormattingOptions]::InsertLineBreaks)
$pem = @"
-----BEGIN CERTIFICATE-----
$certBase64
-----END CERTIFICATE-----
"@
Out-File -FilePath "C:\Users\pnfst\Documents\IISExpress\iis_ssl_server_certificate.pem" -InputObject $pem -Encoding ascii
Import-Module WebAdministration
New-WebBinding -Name "Default Web Site" -IPAddress "192.168.100.2" -Port 443 -HostHeader "localhost" -Protocol "https" -SslFlags 1
$binding = Get-WebBinding -Name "Default Web Site" -Port 443 -Protocol "https"
$binding.AddSslCertificate($cert.Thumbprint, "My")
Set-WebConfiguration -Location "Default Web Site" -Filter "system.webServer/security/access" -Value "Ssl"
Restart-WebItem -PSPath "IIS:\Sites\Default Web Site"
Затем я использовал созданный pem для импорта сертификата в хранилище доверенных сертификатов пользователя Android. Я также добавил этот pem-файл в папку Platforms\Android\Resources\raw моего приложения, установил действие сборки AndroidResource и создал AndroidResource network_security_config.xml в папке Platforms\Android\Resources\xml со следующим содержимым.

Код: Выделить всё



localhost
192.168.100.2





И добавил ссылку на эту конфигурацию сетевой безопасности в свой AndroidManifest: Однако ни один из этих шагов не решил проблему.

Когда я подключаюсь к указанному ранее IP-адресу из веб-браузера Android, он каждый раз запрашивает сертификат и успешно подключается после его выбора.

Я также протестировал https-соединение с IP-адресом локального хоста IIS с помощью openssl, как рекомендовано. Он вернул «Проверьте код возврата: 0 (ок)». Это результат.

Изображение
После того, как я удалил и воссоздал привязку в IIS, openssl выдал мне следующее результат.

Код: Выделить всё

PS C:\Users\pnfst\Documents\IISExpress>  openssl s_client -debug -connect 192.168.100.2:443
Connecting to 192.168.100.2
CONNECTED(00000004)
write to 0xa0007bef0 [0xa00082770] (299 bytes => 299 (0x12B))
0000 - 16 03 01 01 26 01 00 01-22 03 03 fd 32 cf 62 a2   ....&..."...2.b.
0010 - 31 bc fc c6 e7 f7 72 2c-8d 80 47 ba d5 86 6d fc   1.....r,..G...m.
0020 - c5 15 b3 b0 66 1e 1d 01-ba 52 b3 20 04 a0 fb b1   ....f....R. ....
0030 - 5e 0d e5 bd 12 ab 80 64-37 de 65 ee 01 64 97 d2   ^......d7.e..d..
0040 - 35 3d 4e eb ea d7 64 dc-da 1c 9d ed 00 3e 13 02   5=N...d......>..
0050 - 13 03 13 01 c0 2c c0 30-00 9f cc a9 cc a8 cc aa   .....,.0........
0060 - c0 2b c0 2f 00 9e c0 24-c0 28 00 6b c0 23 c0 27   .+./...$.(.k.#.'
0070 - 00 67 c0 0a c0 14 00 39-c0 09 c0 13 00 33 00 9d   .g.....9.....3..
0080 - 00 9c 00 3d 00 3c 00 35-00 2f 00 ff 01 00 00 9b   ...=. 5 (0x5))
0000 - 16 03 03 00 7a                                    ....z
read from 0xa0007bef0 [0xa001aa7b8] (122 bytes => 122 (0x7A))
0000 - 02 00 00 76 03 03 43 0c-5f 12 d5 1f 7f 33 bf 5a   ...v..C._....3.Z
0010 - 8b fe 95 fc 5b dd 2d 13-96 20 47 82 41 41 e1 06   ....[.-.. G.AA..
0020 - 16 b6 8f 39 87 3c 20 04-a0 fb b1 5e 0d e5 bd 12   ...9.< ....^....
0030 - ab 80 64 37 de 65 ee 01-64 97 d2 35 3d 4e eb ea   ..d7.e..d..5=N..
0040 - d7 64 dc da 1c 9d ed 13-02 00 00 2e 00 2b 00 02   .d...........+..
0050 - 03 04 00 33 00 24 00 1d-00 20 ab 99 a5 46 9c 4f   ...3.$...  ...F.O
0060 - fb 9d bc b9 92 e9 d6 60-95 03 33 d2 65 68 d6 dc   .......`..3.eh..
0070 - 8f 98 a1 c2 88 26 4f 11-d7 05                     .....&O...
read from 0xa0007bef0 [0xa001aa7b3] (5 bytes => 5 (0x5))
0000 - 14 03 03 00 01                                    .....
read from 0xa0007bef0 [0xa001aa7b8] (1 bytes => 1 (0x1))
0000 - 01                                                .
read from 0xa0007bef0 [0xa001aa7b3] (5 bytes => 5 (0x5))
0000 - 17 03 03 04 a6                                    .....
read from 0xa0007bef0 [0xa001aa7b8] (1190 bytes =>  1190 (0x4A6))
0000 - 59 a7 02 e9 10 79 57 10-73 34 ae e3 0f 2d f5 43   Y....yW.s4...-.C
0010 - 14 67 9d 56 71 4c ce ec-48 2e 4d 91 8e b1 c5 3d   .g.VqL..H.M....=
0020 - 64 4d c1 4b 4d 63 5b 8f-29 2b 0c 79 fb 5d b0 53   dM.KMc[.)+.y.].S
0030 - 73 4c b3 f4 0a 6c 43 53-83 76 7c 24 08 32 63 b9   sL...lCS.v|$.2c.
0040 - d1 e5 7d 18 be 15 98 3b-54 dd e7 f6 05 ca 79 02   ..}....;T.....y.
0050 - 69 c9 79 d7 72 1d b0 69-6d b6 87 c6 59 d0 3a 23   i.y.r..im...Y.:#
0060 - e5 5f 56 40 76 15 93 b8-ce 85 82 24 c0 81 9c 69   ._V@v......$...i
0070 - 20 60 70 ab 15 8b df 72-25 14 16 e8 39 6f ac 77    `p....r%...9o.w
0080 - 68 c9 40 11 48 76 23 d0-c2 d3 d4 34 68 8d 9b 7f   h.@.Hv#....4h...
0090 - ea 88 a8 3e 4a 57 54 24-96 14 b6 17 7e 77 73 70   ...>JWT$....~wsp
00a0 - 6b 48 8b bd 33 84 f1 93-23 c7 87 77 1b 1e a3 85   kH..3...#..w....
00b0 - 8d 95 d5 cf 65 03 4e 2e-ff 8a 89 a0 8e 32 bb 08   ....e.N......2..
00c0 - 54 0e f9 d2 7e c0 6b 42-57 11 fe e1 e7 74 a5 6e   T...~.kBW....t.n
00d0 - 55 88 80 29 66 d2 c3 ae-70 5b 86 66 b5 b5 e4 95   U..)f...p[.f....
00e0 - 9e c5 c4 45 a2 92 b3 3f-fd a6 33 82 4c a1 82 26   ...E...?..3.L..&
00f0 - 55 65 f2 89 df ed 53 68-27 e1 68 cb a6 bd 1e 4c   Ue....Sh'.h....L
0100 - 7f 87 70 55 9b fd 6a eb-ee 03 bf 0e 60 4b 06 17   ..pU..j.....`K..
0110 - 08 b9 5d ed a7 a1 53 36-6d 98 99 b1 01 fc 3c 63   ..]...S6m.....

Подробнее здесь: [url]https://stackoverflow.com/questions/79797621/how-to-resolve-sslpeerunverifiedexception-hostname-not-verified-in-httpsurlconn[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»