事情是這樣的,我們後端的小夥伴升級了用戶會員系統,使用了全新的GraphQL登錄機制,並且採用SSL加密的方式來實現阻止陌生客戶端請求的案例。
GraphQL在UWP端的實現,以後有時間會單獨寫一篇文章,這裏先說一下怎麼在UWP裏面使用SSL證書的問題。
其實接這個任務也是一個臨時調研的,畢竟企業級SSL證書需要花錢買,而我們只是在內部先做一下,測試。
然後後端小夥伴給了一個測試的證書,並且導出了各種格式。
畢竟我對這個領域完全陌生,就像前面提到的那個GraphQL一樣,蒙圈的那種。
但是工作還是要繼續的,於是Google一頓猛於虎的搜索🔍,終於找到了一些指引。
1. 添加Capabilities
勾選 Shared User Certificates
2. 添加Declarations
在Available Declarations裏面選擇Certificates,然後點擊Add即可。
這一步需要注意,網上有的教程說需要勾選 Exclusive trust。還要在最底下Certificates,點擊Add New,設置Store name以及Content。
看你需要吧,我沒做。也不懂這是幹嘛的。😳
3. 添加SSL證書文件
右擊解決方案,選擇你的SSL證書,並且把Build Action改爲Content。
UWP裏面我嘗試了pfx和p12格式的,均可以正常使用。
其他的證書格式未驗證。
4. 添加HttpClient代碼
protected async override void OnNavigatedTo(NavigationEventArgs e) {
//Wrong method to import cert //StorageFile certificateFile = await Package.Current.InstalledLocation.GetFileAsync(@"client.p12"); //IBuffer certificateBuffer = await FileIO.ReadBufferAsync(certificateFile); //string encodedCertificate = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(certificateBuffer); //await CertificateEnrollmentManager.ImportPfxDataAsync(encodedCertificate, "000000", ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "Client Certificate");
//Better use it this way. Add cert to HttpClientHandler var handler = new HttpClientHandler(); handler.ClientCertificateOptions = ClientCertificateOption.Manual; X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes("client.pfx"), "000000"); handler.ClientCertificates.Add(cer); HttpClient client = new HttpClient(handler); HttpResponseMessage response = await client.GetAsync("https://test.client.ssl/"); //HttpResponseMessage response = await client.GetAsync("https://192.168.101.99/"); response.EnsureSuccessStatusCode(); string temp = await response.Content.ReadAsStringAsync(); }
然後別忘了添加引用
using System; using System.IO; using System.Net.Http; using System.Security.Cryptography.X509Certificates; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation;
5. Done!!!
如果成功訪問指定的ip,並且獲取到了數據的話,那麼說明完成了。