c# - 使用 Box Windows SDK v2 库在 C# 桌面应用程序中对 Box 进行身份验证

标签 c# oauth-2.0 box-api

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

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

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

最佳答案

我决定自己尝试解决这个问题。尽管 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");
}

其余代码只是您的普通身份验证代码,它使用 token 和来自先前请求的诸如此类的东西来获取更多 token 等。Box 使用“refresh_tokens”来让您获得额外的访问 token ,我也展示了一个如何做到这一点的例子。

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

关于c# - 使用 Box Windows SDK v2 库在 C# 桌面应用程序中对 Box 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124152/

相关文章:

ios - Box api 编辑文件

oauth-2.0 - OAuth2 中的永久访问 token

c# - IMethodInvocation 中参数和输入的区别

c# - 如何使用 CSS 在同一行上对齐两个文本框

api - 生成访问 token 并通过 Azure API 管理针对 IdentityServer4 进行验证

azure - Microsoft 帐户的用户 id 是否与 ID token 中的 oid 声明相同?

box-api - 如何增强 Box.com API 请求限制

C# 检查对象是否属于仅在运行时已知的类型

c# - emgucv:C#中的Pan Card不当偏斜检测

azure - 通过 SPA 上的 API 调用传递 Azure token (JWT)