2018年11月13日 星期二

[ASP.Net MVC] Github OAuth外部驗證無法使用(要求已經中止: 無法建立 SSL/TLS 的安全通道/loginInfo為null)

前言:
OAuth是一種外部驗證的標準,可讓第三方應用程式,存取資源擁有者的資源。
通過驗證後,第三方應用程式會從OAuth Server拿到token,
即可使用token存取資源伺服器上的資源了。

.Net MVC 5預設有提供外部驗證(Google、FB、Microsoft與Twitter等),
如要使用Github OAuth驗證,NuGet上也有package可直接使用:
裝好package後,打開Startup.Auth.cs,
輸入app.UseGitHubAuthentication("clientID", "clientSecret");
基本上就可使用了。

需啟用https,才可以進行OAuth驗證。

不過在本機使用.Net framework 4.5.2+MVC 5.2.3驗證卻無法登入:
按下外部登入的GitHub按鈕,狀態列顯示瀏覽器在動作,但過了一會,
發現畫面依然停留在登入畫面,WTF??

取得Owin.Security.Providers.GitHub的source code來trace,
發現在發request要token這裡,
出現Exception:「要求已經中止: 無法建立 SSL/TLS 的安全通道」,
(The request was aborted: Could not create SSL/TLS secure channel.)
導致ExternalLoginCallback中loginInfo為null,又回到Login頁面。

那為何出現該Exceptioin? 參考黑大與其他文章,
原來是.Net 4.5預設https的protocol是TLS 1.0,但TLS 1.0因安全性問題,
已被大家捨棄,使用TLS 1.2以上是現行的做法。

解決辦法:
● 因.Net 4.6預設使用TLS 1.2,新專案可直接使用framework 4.6以上,試過ok,直接升級framework試過不行。
● 若是參考source code,可以在handler要token前的request加入:
 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolTypeExtensions.Tls12;

● 修改registry機碼,將環境改為TLS 1.2,可參考下圖。



參考資料:
https://tools.ietf.org/html/rfc6749#section-1.3.1
https://blog.darkthread.net/blog/disable-tls-1-0-issues
https://support.microsoft.com/en-us/help/3154520/support-for-tls-system-default-versions-included-in-the-net-framework