我决定自己尝试解决这个问题。尽管 OAuth2 支持基于非浏览器的身份验证,但显然 Box.com 已决定不实现它(或者,至少,我在任何地方都找不到如何实现它的提及)。
因此,基于桌面的应用程序的唯一替代方案是以某种方式拦截发生的 URL 重定向,并从查询字符串参数中提取身份验证信息。
然而,由于 IE 最近已经落后于时代,而我正在使用 C# 和 .NET,我决定考虑嵌入另一个浏览器,而不是使用内置的浏览器控件。我和敬畏者 https://www.awesomium.com/--托管.NETChromium http://www.chromium.org/包装纸。
因此,言归正传,我将介绍适用于桌面应用程序的简单示例。
我的解决方案有两种形式,一种纯粹用作“浏览器”,另一种是主形式: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”来使您能够获取额外的访问令牌,我展示了一个也有如何做到这一点的示例。
如果您发现任何错误或有任何意见等,请发表评论。