【UWP】手動實現 WebAuthenticationBroker

来源:https://www.cnblogs.com/h82258652/archive/2019/04/09/10677504.html
-Advertisement-
Play Games

在 UWP 中,如果要進行 OAuth 授權,那很大概率是會用上 WebAuthenticationBroker 這個類的,例如微博授權這種。 在一般情況下來說,WebAuthenticationBroker 是足夠用的了,但是,如果你是碰上 Github 授權的話,那麼就會碰到這樣的情況: 蹦出一 ...


在 UWP 中,如果要進行 OAuth 授權,那很大概率是會用上 WebAuthenticationBroker 這個類的,例如微博授權這種。

在一般情況下來說,WebAuthenticationBroker 是足夠用的了,但是,如果你是碰上 Github 授權的話,那麼就會碰到這樣的情況:

Snipaste_2019-04-09_09-33-53

蹦出一大個警告,讓人看上去相當不爽。歸根的原因是 WebAuthenticationBroker 使用的是 IE 內核,這個我們可以通過 https://www.whatismybrowser.com/ 驗證。

Snipaste_2019-04-09_09-36-59

連 Edge 內核都不是,不給力啊,老濕。

 

那麼有沒有辦法把 WebAuthenticationBroker 換成 Edge 內核呢?簡單的辦法是沒有的了,但我們還有 WebView,WebView 是使用 Edge 內核的,可以通過 WebView 來手動實現我們自己的 WebAuthenticationBroker。

參考 WebAuthenticationBroker 類的 AuthenticateAsync,編寫如下代碼:

public static class MyWebAuthenticationBroker
    {
        public static Task<MyWebAuthenticationResult> AuthenticateAsync(Uri requestUri, Uri callbackUri)
        {
            throw new NotImplementedException();
        }
    }

WebAuthenticationBroker 的 AuthenticateAsync 這個方法有 3 個參數,但第一個參數並不是很常用,所以這裡就只使用後面的兩個參數了。另外因為 WebAuthenticationResult 沒有公共構造函數,所以定義一個 MyWebAuthenticationResult 來代替。

public class MyWebAuthenticationResult
    {
        public string ResponseData { get; internal set; }

        public uint ResponseErrorDetail { get; internal set; }

        public WebAuthenticationStatus ResponseStatus { get; internal set; }
    }

接下來就是如何實現的問題。這裡我們可以使用一個 ContentDialog 套 WebView 的方式。

在項目添加一個內容對話框(這裡我叫 AuthorizationDialog),並編寫如下代碼:

<ContentDialog x:Class="WebAuthenticationBrokerDemo.AuthorizationDialog"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
               Title="正在連接到服務"
               CloseButtonText="取消"
               FullSizeDesired="True"
               mc:Ignorable="d">
    <ContentDialog.Resources>
        <ResourceDictionary>
            <x:Double x:Key="ContentDialogMinWidth">800</x:Double>
        </ResourceDictionary>
    </ContentDialog.Resources>
    <Grid>
        <WebView x:Name="WebView"
                 NavigationFailed="WebView_NavigationFailed"
                 NavigationStarting="WebView_NavigationStarting" />
    </Grid>
</ContentDialog>

設置 FullSizeDesired 使高度占滿視窗,資源字典中覆蓋預設的對話框寬度。WebView 則訂閱 Starting 和 Failed 事件。編寫後臺 cs 代碼:

public sealed partial class AuthorizationDialog
    {
        private readonly Uri _callbackUri;

        public AuthorizationDialog(Uri requestUri, Uri callbackUri)
        {
            if (requestUri == null)
            {
                throw new ArgumentNullException(nameof(requestUri));
            }
            if (callbackUri == null)
            {
                throw new ArgumentNullException(nameof(callbackUri));
            }

            _callbackUri = callbackUri;

            InitializeComponent();

            WebView.Source = requestUri;
        }

        public Uri ResponseUri { get; private set; }

        public WebAuthenticationStatus Result { get; private set; } = WebAuthenticationStatus.UserCancel;

        public WebErrorStatus WebErrorStatus { get; private set; }

        private bool CheckUri(Uri uri)
        {
            if (uri.Host == _callbackUri.Host)
            {
                Result = WebAuthenticationStatus.Success;
                ResponseUri = uri;
                return true;
            }

            return false;
        }

        private void WebView_NavigationFailed(object sender, WebViewNavigationFailedEventArgs e)
        {
            if (CheckUri(e.Uri))
            {
                Hide();
                return;
            }

            Result = WebAuthenticationStatus.ErrorHttp;
            ResponseUri = e.Uri;
            WebErrorStatus = e.WebErrorStatus;
            Hide();
        }

        private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            if (CheckUri(args.Uri))
            {
                Hide();
            }
        }
    }

可以通過 Hide 方法來關閉對話框。需要註意的是 Failed 的時候需要先檢查一次,因為可能 callback 的地址是無法訪問的。

接下來可以補完一開始的 AuthenticateAsync 方法了。

public static class MyWebAuthenticationBroker
    {
        public static async Task<MyWebAuthenticationResult> AuthenticateAsync(Uri requestUri, Uri callbackUri)
        {
            var authorizationDialog = new AuthorizationDialog(requestUri, callbackUri);
            await authorizationDialog.ShowAsync();
            if (authorizationDialog.Result == WebAuthenticationStatus.UserCancel)
            {
                return new MyWebAuthenticationResult
                {
                    ResponseStatus = WebAuthenticationStatus.UserCancel
                };
            }
            else if (authorizationDialog.Result == WebAuthenticationStatus.Success)
            {
                return new MyWebAuthenticationResult
                {
                    ResponseStatus = WebAuthenticationStatus.Success,
                    ResponseData = authorizationDialog.ResponseUri.OriginalString
                };
            }
            else
            {
                return new MyWebAuthenticationResult
                {
                    ResponseStatus = WebAuthenticationStatus.ErrorHttp,
                    ResponseData = authorizationDialog.ResponseUri.OriginalString,
                    ResponseErrorDetail = (uint)authorizationDialog.WebErrorStatus
                };
            }
        }
    }

那麼現在我們再去連 Github 之類的授權就不會有警告了,因為內核已經換成了 Edge。

Snipaste_2019-04-09_15-56-26

而且因為是使用 WebView,所以還能再進行一些定製化的操作,例如執行 JavaScript,獲取 Cookie 之類的。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 每種方法中上面的是Excel的行數,下麵的是Excel的列數。方法七:經過加工修改已經可以讀出來的是有效數據行 using Excel = Microsoft.Office.Interop.Excel;//Excel表讀寫 Excel.Application app = new Excel.Appl ...
  • 原文鏈接:https://www.entityframeworktutorial.net/code-first/stringlength-dataannotations-attribute-in-code-first.aspx StringLength特性可以應用於實體的string類型的屬性上,它 ...
  • 原文鏈接:https://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspx MaxLength特性指定了屬性的值所允許的最大值,然後在 ...
  • 最近在學WebSocket,服務端需要監聽多個WebSocket客戶端發送的消息。 開始的解決方法是每個WebSocket客戶端都添加一個線程進行監聽,代碼如下: /// <summary> /// 監聽埠 創建WebSocket /// </summary> /// <param name="h ...
  • 備註:本人使用開發工具:VS2017,.NET Core 2.2,其中VS2017原本自帶2.1,我單獨從官網下載了2.2的程式集安裝包,但是沒有下配套的運行環境,運行項目時出了一個問題。 以下是我在發佈Core項目後部署到IIS後運行時遇到的一些問題: 1-發佈設置: 在發佈過程中,項目一直還原n ...
  • [CommandMethod("CBline")] //對稱畫線 public void CBline() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor edit = doc.Editor; Databa ...
  • 主要代碼: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using GrxCAD.Runtime;using GrxCAD ...
  • 基於浩辰CAD2019 需求: 開發線轉圓簡單命令。命令過程:1) 請選擇圖中直線(要求支持一次選多個):2) 彈出對話框,輸入圓的圖層名和半徑3) 點對話框中確定按鈕,結束命令。命令執行效果:所選每條直線的起點和終點處,自動生成兩個圓;同時,所有直線自動整體平移MOVE一個向量AcGeVector ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...