【问题标题】:Authentication to Box in a C# desktop application using the Box Windows SDK v2 library使用 Box Windows SDK v2 库在 C# 桌面应用程序中对 Box 进行身份验证
【发布时间】:2014-04-03 03:59:43
【问题描述】:

看起来这应该是一件简单的事情,但我找不到示例或足够详尽的文档来弄清楚。

我有一个 C# 桌面应用程序,我想通过 Box API 与 Box 集成。我认为使用适用于 .NET 的 Box Windows SDK v2 将是可行的方法。

谁能给我指出一个适用于桌面应用程序的简单、简单的示例?

【问题讨论】:

    标签: c# oauth-2.0 box-api


    【解决方案1】:

    我决定自己尝试解决这个问题。尽管 OAuth2 支持基于非浏览器的身份验证,但显然 Box.com 已决定不实施它(或者,至少,我在任何地方都找不到有关如何实施的信息)。

    因此,基于桌面的应用程序的唯一替代方法是以某种方式拦截发生的 URL 重定向并将身份验证信息从查询字符串参数中提取出来。

    但是,由于 IE 最近落后于时代,而且我正在使用 C# 和 .NET,我决定考虑嵌入另一个浏览器,而不是使用内置的浏览器控件。我选择了Awesomium——一个托管的.NET Chromium 包装器。

    因此,事不宜迟,我将介绍适用于桌面应用程序的简单示例。

    我的解决方案有两种形式,一种纯粹用作“浏览器”,一种是主要形式:frmMain 包含所有代码,frmBrowser 包含 Awesomium 控件。

    using Newtonsoft.Json.Linq;
    using System.Web;
    
    private static frmBrowser browser = null;
    private const string BoxClientId = "{your client id}";
    private const string BoxSecret = "{your secret}";    
    
    private void authenticateWithBox()
    {
       browser = new frmBrowser();
       browser.Show();
    
       browser.webControl1.Source = new Uri("https://www.box.com/api/oauth2/authorize?response_type=code&client_id=" + BoxClientId + "&redirect_uri=https://localsess");
       browser.webControl1.AddressChanged += new Awesomium.Core.UrlEventHandler(webControl1_AddressChanged);
    }
    
    void webControl1_AddressChanged(object sender, Awesomium.Core.UrlEventArgs e)
    {
      //MessageBox.Show(e.Url.ToString());
      if (e.Url.Host == "localsess")
      {
        NameValueCollection parms = HttpUtility.ParseQueryString(e.Url.Query);
        if (parms.AllKeys.Contains("error"))
        {
           MessageBox.Show("Error connecting to Box.com: " + parms["error"] + " " + parms["error_description"]);
        }
        else
        {
            boxContinue(parms["code"]);
        }
      }
    }
    

    上面的代码是魔法发生的地方。每次 Web 控件显示的 URL 发生更改时,都会触发 AddressChanged 事件。因此,您必须将重定向 URL 设置为您可以检测到的唯一内容——它甚至不必存在,如示例代码所示。然后你就可以抽出你需要的参数并继续认证过程。

    string postToUrl(string url, string data)
    {
      string results = String.Empty;
      WebRequest req = WebRequest.Create(url);
      req.Method = WebRequestMethods.Http.Post;
      byte[] byteArray = Encoding.UTF8.GetBytes(data);
      req.ContentType = "application/x-www-form-urlencoded";
      req.ContentLength = byteArray.Length;
      Stream dataStream = req.GetRequestStream();
      dataStream.Write(byteArray, 0, byteArray.Length);
      dataStream.Close();
      WebResponse res = req.GetResponse();
      dataStream = res.GetResponseStream();
      StreamReader reader = new StreamReader(dataStream);
      results = reader.ReadToEnd();
      return results;
    }
    
    void boxContinue(string code)
    {
      browser.Close();
      browser.Dispose();
      string json = postToUrl("https://www.box.com/api/oauth2/token", "code=" + code + "&grant_type=authorization_code&client_id=" + BoxClientId + "&client_secret=" + BoxSecret);
      JToken token = JObject.Parse(json);
    
      string access_token = (string)token.SelectToken("access_token");
      string refresh_token = (string)token.SelectToken("refresh_token");
    }
    
    void boxRefresh(string refresh_token)
    {
      string json = postToUrl("https://www.box.com/api/oauth2/token", "grant_type=refresh_token&refresh_token=" + refresh_token + "&client_id=" + BoxClientId + "&client_secret=" + BoxSecret);
      JToken token = JObject.Parse(json);
    
      string access_token = (string)token.SelectToken("access_token");
      string new_refresh_token = (string)token.SelectToken("refresh_token");
    }
    

    其余代码只是您的普通身份验证代码,它使用令牌和以前请求中的其他内容来获取更多令牌等。Box 使用“refresh_tokens”使您能够获得额外的访问令牌,我也举了一个例子来说明如何做到这一点。

    如果您发现任何错误或有任何 cmet 等,请发表评论。

    【讨论】:

    • 我已经尝试过您的posturl function 来检索JSon。但我收到错误The remote server returned an error: (400) Bad Request.。需要帮助我在这里缺少什么?
    • 我已通过身份验证并从default browser 获得code
    • 是的,非常感谢你,伙计。 :)
    【解决方案2】:

    请确保您使用的是 Box SDK 的官方 v2 版本: https://github.com/box/box-windows-sdk-v2

    解决方案中有一个完整的 WPF 示例可帮助您入门。如果您遇到任何其他问题,请随时在 github 页面的问题部分留言。

    【讨论】:

    • 所以,我猜你要告诉我的是,如果不使用浏览器控件并在授权被授予或撤销后拦截重定向,就无法授权 Box?
    • 这就是OAuth 2的本质。初始授权请求需要经过box.com/api/oauth2/authorize。后续授权请求可以使用刷新令牌完成,无需 web 视图。
    • 然后,是否可以向用户显示授权屏幕,等待大约 15 秒,然后,假设用户授予您访问权限,尝试执行您刚才所说的刷新代币?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多