无法使用 Xamarin.Forms WebView 进行 Dropbox 身份验证

Posted

技术标签:

【中文标题】无法使用 Xamarin.Forms WebView 进行 Dropbox 身份验证【英文标题】:Unable to use Xamarin.Forms WebView for Dropbox authentication 【发布时间】:2018-05-10 22:35:38 【问题描述】:

我在使用 WebView 访问授权我的 Xamarin 表单(在 ios 下运行)应用程序访问所需的授权 uri 时遇到了问题。我不认为问题出在 WebView 和特定的 url,而不是 Dropbox API 本身。

首先,我应该提到我能够使用 WebView 访问任意网站,所以我知道我可以从我的应用程序中访问网络。

在下面的代码中,您会看到我设置了两个按钮。第一个使用 WebView 成功访问 Xamarin 的 Wikipedia 页面。第二次尝试联系 Dropbox 以开始身份验证过程。但是,该请求失败并显示以下消息:

错误 (400) 您使用的应用程序似乎提交了错误的请求。如果您想将此错误报告给应用程序的开发者,请提供以下信息。无效的redirect_uri。必须是绝对 uri。

最初,我认为问题在于重定向 uri 没有正确注册,但如果我将传递给 webview 的 url 复制(包含在下面作为评论),并将其直接粘贴到 safari 中,身份验证页面按预期打开。只有在使用 WebView 时,我才会收到错误消息。这让我认为这不是redirect_uri 或url 本身,而是WebView 将其呈现给dropbox.com 的方式。

谁能帮帮我?我还尝试了一个在 Safari / Chrome 中工作的 uri,并将其直接传递给 webview(绕过 DropboxOAuth2Helper),但没有任何运气。 uri 可以在 Safari 中使用,但不能在 WebView 中使用。

public App()

    Button xamarinBtn = new Button();
    xamarinBtn.Text = "Xamarin";
    xamarinBtn.Clicked += OnButtonClicked;
    xamarinBtn.StyleId = "Xamarin";

    Button dropboxBtn = new Button();
    dropboxBtn.Text = "Dropbox";
    dropboxBtn.Clicked += OnButtonClicked;
    dropboxBtn.StyleId = "Dropbox";

    StackLayout layout = new StackLayout();
    layout.Children.Add(xamarinBtn);
    layout.Children.Add(dropboxBtn);

    ContentPage page = new ContentPage();
    page.Content = layout;

    MainPage = new NavigationPage(page);


private void OnButtonClicked(object sender, EventArgs e)

    Button btn = sender as Button;

    UrlWebViewSource source = new UrlWebViewSource();
    if (btn.StyleId == "Xamarin")
    
            source.Url = "https://en.wikipedia.org/wiki/Xamarin";
    
    else if (btn.StyleId == "Dropbox")
    
        string oauth2State = Guid.NewGuid().ToString("N");
        Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, "d1612up7la63slo", "http://127.0.0.1:52475/authorize", oauth2State);
        source.Url = authorizeUri.AbsoluteUri; // https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=d1612up7la63slo&redirect_uri=http%3A%2F%2F127.0.0.1%3A52475%2Fauthorize&state=1062a614aa3d4e2e85cd84de32903987
    

    WebView webView = new WebView();
    webView.Source = source;

    ContentPage page = new ContentPage();
    page.Content = webView;

    MainPage.Navigation.PushAsync(page);

【问题讨论】:

如果您不想在登录 Dropbox 时排除 Google 帐户,则无论如何都必须切换到外部浏览器才能进行身份验证。使用 WebView 是由 Google 提供的deprecated,将来可能还会由其他人使用。这使开发人员的事情变得更加复杂,但最终对用户来说更安全。 【参考方案1】:

您应该通过应用控制台将其添加为您的应用的 OAuth 2 重定向 URI: 完成此操作后,我尝试了 OC 代码,它可以正常工作并且可以显示授权视图。但不幸的是,Xamarin 的 Dropbox 失败了。您可以尝试使用其他 api 来显示此视图:

Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri("d1612up7la63slo");
source.Url = source.Url = authorizeUri.AbsoluteUri;

【讨论】:

以上是关于无法使用 Xamarin.Forms WebView 进行 Dropbox 身份验证的主要内容,如果未能解决你的问题,请参考以下文章