I am trying to implement Googleplus login on my site using Oauth2.
I would like to pass state parameter which will be used once the user is successfully authenticated.
The error i am getting is "OAuth 2 parameters can only have a single value: code".
If i do not use the state parameter, it is working fine and authenticating the user.
Below is my code:
protected void Page_Load(object sender, EventArgs e)
{
string returnPath = Request.QueryString["ReturnUrl"];
if (returnPath == null)
{
returnPath = "ManageAccount.aspx";
}
else
{
returnPath = Request.QueryString["ReturnUrl"].ToString();
}
Session["state"] = returnPath;
if (Session["Provider"] != null)
{
if (Session["Provider"].ToString() == "Google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
getgoogleplususerdataSer(accessToken);
}
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
lblMessage.Text = error;
}
}
}
}
}
}
}
protected void btnGoogleLogin_Click(object sender, System.EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id + "&state=" + Session["state"];
Session["Provider"] = "Google";
Response.Redirect(Googleurl);
}
What could i be doing wrong?
I decided to avoid the state parameter. Instead i stored the ReturnUrl in a cookie for use after successful authentication.
returnPath = Request.QueryString["ReturnUrl"];
if (returnPath == null)
{
returnPath = "ManageAccount.aspx";
}
else
{
returnPath = Request.QueryString["ReturnUrl"].ToString();
}
//Create a cookie to redirect user after login
HttpCookie rCookie = new HttpCookie("RedirectCookie");
DateTime now = DateTime.Now;
rCookie.Value = returnPath;
Response.Cookies.Add(rCookie);
Related
I have an application where I used signalr. and formAuthentication. I am trying to connect hub class from WCF service. IN WCF service code is as bellow:
Public Class Demo
{
public Demo()
{
var connection = new HubConnection("http://localhost:47315/")
{
CookieContainer = new CookieContainer()
};
connection.CookieContainer.Add(GetAuthCookie("user1", "pass"));
chatHubProxy = connection.CreateHubProxy("servicesSatatuseHub");
connection.Start().Wait();
}
private static System.Net.Cookie GetAuthCookie(string user, string pass)
{
//var http = WebRequest.Create("http://localhost:47315/module/account/login.aspx") as HttpWebRequest;
var http = WebRequest.Create("http://localhost:47315//module/account/login.aspx") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
//var postData = "UserName=" + user + "&Password=" + pass + "";
var postData = "UserName=" + user + "&Password=" + pass + "";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
System.Net.Cookie authCookie;
using (var response = http.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
}
httpResponse.Close();
return cookie;
}
}
Every thing is fine but Cookie is null on this code
authCookie = <p>response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
Due to cookie null hubconnection is fail.
Thanks in advance
I wonder if someone can give me some pointers on using the linked in API. I thought I had it sussed but for some reason when trying to get the auth_token I just get http 400 Bad Request.
My code, simply is:
public string redirectUrl = URLTOREDIRECT;
public String apiKey = APIKEY;
public String apiSecret = APISECRET;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=apiKey&scope=rw_company_admin&state=DCEEFWF45453sdffef424&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl));
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + _consumerkey + "&client_secret=" + _consumerSecret;
// var postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code, HttpUtility.HtmlEncode(redirectUrl), apiKey, apiSecret);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
//This "application/x-www-form-urlencoded"; line is important
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = sign.Length;
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(sign);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
return responseReader.ReadToEnd().ToString() ;
}
The code is all in the same page for testing purposes and is the same page as the redirectUrl.
Really stumped, tried all variations.
First bit clearly works as I get directed to linked in to allow app. The second part getting the auth token fails.
After much head scratching, eureka moment - did not need to send the info in the request.
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
//byte[] byteArray = Encoding.UTF8.GetBytes(sign);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
return returnVal;
I'm Using this code and it's working fine..... C# code ASP.NET :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LI
{
public partial class WebForm3 : System.Web.UI.Page
{
public string redirectUrl = "http://localhost:64576/WebForm3";
public string TokenGlobe = "";
public String apiKey = "API_KEY";
public string retval = "";
public String apiSecret = "API_Secret";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void btnTwit_Click(object sender, EventArgs e)
{
var Address = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + apiKey + "&redirect_uri=http://localhost:64576/WebForm3&state=987654321&scope=w_share";
using (var webClient = new WebClient())
{
webClient.Headers.Add("x-li-format", "json");
}
Response.Redirect(Address);
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/oauth/v2/accessToken";
var sign1 = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" + apiKey + "&client_secret=" + apiSecret + "";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
HttpWebRequest webRequest = System.Net.WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Host = "www.linkedin.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
var stri = redirectUrl;
retval = returnVal.ToString();
var objects = JsonConvert.DeserializeObject<Accountdsdsd>(retval);//JArray.Parse(retval);
TokenGlobe = objects.access_token;
var SentStatus = PostLinkedInNetworkUpdate(TokenGlobe, "Hello API"); //Share
return TokenGlobe;
// return responseReader.ReadToEnd().ToString();
}
private string linkedinSharesEndPoint = "https://api.linkedin.com//v1/people/~/shares?oauth2_access_token={0}&format=json";
private const string defaultUrl = "http://localhost:64576/WebForm3";
private const string defaultImageUrl = "http://opusleads.com/opusing/technology/technology%20(1).jpg"; //Image To Post
public bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = defaultUrl, string submittedImageUrl = defaultImageUrl)
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
//Json Parsing
public class Accountdsdsd
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
}
The following code gets stuck in a while loop when an exception is encountered. This is because GetResponse is caching the data.
According to fiddler, no data after the first request is issued.
Is it a best practice to recreate the webclient to solve the "refresh" issue I'm having?
private static ReportStatusEnum GetReportStatus(string domain, string oAuthKey, long permissionReportID)
{
string target = string.Format("https://{0}.egnyte.com/pubapi/v1/audit/jobs/{1}", domain, permissionReportID);
var client = new WebClient();
string result ="";
var request = (HttpWebRequest)WebRequest.Create(target);
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + oAuthKey);
request.AllowAutoRedirect = false;
bool callComplete = false;
while (callComplete != true)
{
try
{
using (var response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
JToken result2 = JObject.Parse(result);
var statusResult = result2.SelectToken("status");
ReportStatusEnum ret = ReportStatusEnum.error;
Enum.TryParse<ReportStatusEnum>(statusResult.ToString(), out ret);
Console.WriteLine("The returned variable is:" + ret);
callComplete = true;
return ret;
}
catch (System.Net.WebException e)
{
if (e.Response != null)
if (e.Response.ContentLength > 0)
{
if (e.Response.Headers["X-Mashery-Error-Code"] == "ERR_403_DEVELOPER_OVER_QPS")
{
Thread.Sleep(60000); Console.Write("*QPS HIT*");
}
}
}
}
return ReportStatusEnum.error;
}
No. HttpWebRequests are not reusable.
Just move the creation of your WebRequest into the body of your loop:
string result ="";
bool callComplete = false;
while (callComplete != true)
{
var request = (HttpWebRequest)WebRequest.Create(target);
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + oAuthKey);
request.AllowAutoRedirect = false;
//...
I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I have been fighting with this upload problem for a couple of days and searched the forum for a good answer but have not seen it yet. I am using asp.net and I am currently receiving a timeout when I try to post a file to upload. I have taken the MultipartWebRequest class from the V1 C# Api and changed it(i believe to be correctly but it may be my problem) to work with my program.
public sealed class MultipartWebRequest
{
public string AcceptCharset { get; set; }
public string AcceptEncoding { get; set; }
public string Url { get; set; }
public string Boundary { get; set; }
public string ApiKey { get; private set; }
public string Token { get; private set; }
public MultipartWebRequest(string apiKey, string token, string submitUrl,string acceptCharset = "ISO-8859-1", string acceptEncoding = "gzip,deflate" )
{
Boundary = "----------------" + DateTime.Now.Ticks;
ApiKey = apiKey;
Token = token;
Url = submitUrl;
AcceptCharset = acceptCharset;
AcceptEncoding = acceptEncoding;
}
public string SubmitFiles(
//string[] filePaths,
UploadableFile[] files,
bool isShared,
string message,
string[] emailsToNotify,
string folderId)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
if (files != null)
{
buffer = AssembleFilesBlock(files, folderId);
resultStream.Write(buffer, 0, buffer.Length);
}
if (!string.IsNullOrEmpty(message))
{
buffer = AssembleMessageBlock(message);
resultStream.Write(buffer, 0, buffer.Length);
}
//buffer = AssembleSharedBlock(isShared);
//resultStream.Write(buffer, 0, buffer.Length);
if (emailsToNotify != null)
{
buffer = AssembleEmailsBlock(emailsToNotify);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(true);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
HttpWebRequest myRequest = CreateRequest(buffer.Length);
using (Stream stream = myRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
string response;
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse())
using (Stream responseStream = myHttpWebResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
response = reader.ReadToEnd();
responseStream.Close();
}
myHttpWebResponse.Close();
return response;
}
private byte[] GetFormattedBoundary(bool isEndBoundary)
{
string template = isEndBoundary ? "--{0}--{1}" : "--{0}{1}";
return Encoding.ASCII.GetBytes(string.Format(template, Boundary, Environment.NewLine));
}
private byte[] AssembleEmailsBlock(string[] emailsToNotify)
{
return new byte[1];
}
private byte[] AssembleSharedBlock(bool isShared)
{
byte[] boundaryContent = GetFormattedBoundary(false);
return new byte[1];
}
private byte[] AssembleMessageBlock(string message)
{
return new byte[1];
}
private byte[] AssembleFilesBlock(UploadableFile[] files, string folderId)
{
byte[] buffer = null;
using (MemoryStream resultStream = new MemoryStream())
{
for (int i = 0; i < files.Length ; i++)
{
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleFile(files[i]);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleStringValue("folder_id", folderId);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private byte[] AssembleStringValue(string paramName, string paramValue)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("Content-Disposition: form-data; name=\"{0}\"{1}", paramName, Environment.NewLine);
result.AppendLine();
result.AppendLine(paramValue);
return Encoding.ASCII.GetBytes(result.ToString());
}
private byte[] AssembleFile(UploadableFile file)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", Guid.NewGuid(), file.FileName, Environment.NewLine));
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes("Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(file.FileContents);
//buffer = File.ReadAllBytes(filePath);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private HttpWebRequest CreateRequest(long contentLength)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Method = "POST";
//webRequest.AllowWriteStreamBuffering = true;
webRequest.ContentType = string.Concat("multipart/form-data;boundary=", Boundary);
webRequest.Headers.Add("Authorization", "BoxAuth api_key=" + ApiKey + "&auth_token=" + Token);
webRequest.Headers.Add("Accept-Encoding", AcceptEncoding);
webRequest.Headers.Add("Accept-Charset", AcceptCharset);
webRequest.ContentLength = contentLength;
webRequest.ServicePoint.ConnectionLeaseTimeout = 0;
return webRequest;
}
}
Here is my default asp.net page... This is mainly just a testing page. And I can to GET requests and login and get the token and folders and everything else.
public partial class _Default : System.Web.UI.Page
{
public const string APIKEY = "{APIKEY}";
public const string AUTH_STRING = "https://www.box.com/api/1.0/auth/";
public const string GET_TOKEN_STRING = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key={0}&ticket={1}";
public const string BASE_URL = "https://api.box.com/2.0/";
public string ticket = "";
public string token = "";
public string login = "";
public BoxUser boxUser;
HttpContext http;
protected void Page_Load(object sender, EventArgs e)
{
http = HttpContext.Current;
ticket = http.Request["ticket"];
token = http.Request["auth_token"];
login = http.Request["login"];
}
protected void btnBoxLogin_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_ticket&api_key=" + APIKEY;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseTicket(xmlString);
}
if(ticket != "")
txtResponse.Text = "\nThe Ticket returned is: " + ticket;
response.Close();
stream.Close();
Response.Redirect(AUTH_STRING + ticket, false);
}
protected void btnGetAuthToken_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key="+APIKEY+"&ticket=" + ticket;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseUser(xmlString);
}
//txtResponse.Text += token + "\n";
//txtResponse.Text += login;
response.Close();
reader.Close();
stream.Close();
}
protected void btnGetUserFolderInfo_Click(object sender, EventArgs e)
{
string usersUrl = "folders/0/items";
string url = BASE_URL + usersUrl;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
JavaScriptSerializer js = new JavaScriptSerializer();
object o = js.DeserializeObject(reader.ReadLine());
if (reader != null)
{
string txt = reader.ReadLine();
txtResponse.Text += "\n" + txt;
while (!reader.EndOfStream)
{
txt = reader.ReadToEnd();
txtResponse.Text += "\n" + txt;
}
}
stream.Close();
response.Close();
reader.Close();
}
private void GetResponseTicket(string xmlString)
{
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("status");
string status = reader.ReadElementContentAsString();
if (status != null && status == "get_ticket_ok")
{
ticket = reader.ReadElementContentAsString();
if (String.IsNullOrEmpty(ticket))
throw new Exception("Ticket was empty");
}
else
throw new Exception("For some reason Status was null or not right");
}
}
private void GetResponseUser(string xmlString)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNode root = doc.DocumentElement;
XmlNode user = root.LastChild;
//XmlNamespaceManager xmlns = new XmlNamespaceManager(doc.NameTable);
//XmlNode node = root.SelectSingleNode(login).InnerText
string login = user.SelectSingleNode("login").InnerText;
string email = user.SelectSingleNode("email").InnerText;
string access_id = user.SelectSingleNode("access_id").InnerText;
string user_id = user.SelectSingleNode("user_id").InnerText;
long space_amount = long.Parse(user.SelectSingleNode("space_amount").InnerText);
long space_used = long.Parse(user.SelectSingleNode("space_used").InnerText);
long max_upload_size = long.Parse(user.SelectSingleNode("max_upload_size").InnerText);
boxUser = new BoxUser(login, email, access_id, user_id, space_amount, space_used, max_upload_size);
}
protected void CreateNewFolder_Click(object sender, EventArgs e)
{
string url = BASE_URL + "folders/389813359";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = "POST";
request.ServicePoint.ConnectionLeaseTimeout = 0;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "{\"name\":\"" + txtNewFolderName.Text+"\"}";
byte[] data = encoding.GetBytes(postData);
using (Stream datastream = request.GetRequestStream())
{
datastream.Write(data, 0, data.Length);
datastream.Close();
}
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
lblResult.Text = responseFromServer;
reader.Close();
stream.Close();
response.Close();
}
protected void UploadNewFile_Click(object sender, EventArgs e)
{
//string url = BASE_URL + "files/data";
string url = "https://upload.box.com/api/2.0/" + "files/data";
//string url = "https://upload.box.com/api/1.0/upload" + token + "/0";
/*string boundary = "----------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
string propFormat = "--" + boundary + newLine + "Content-Disposition: form-data; {0}={1}" + newLine;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
string fileName = fileUpload.FileName;
byte[] file = fileUpload.FileBytes;
using (Stream stream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(stream);
string tmp = String.Format(propFormat, fileName, file);
writer.Write(tmp);
tmp = String.Format(propFormat, "folder_id", "389813359");
writer.Write(tmp);
writer.Write("--" + boundary + "--");
writer.Flush();
}
WebResponse response = request.GetResponse();
using (Stream resStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(resStream);
lblResult.Text = reader.ReadToEnd();
}*/
Stream stream = fileUpload.PostedFile.InputStream;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
UploadableFile file = new UploadableFile(fileUpload.FileName, text, ".txt");
UploadableFile[] files = new UploadableFile[1];
files[0] = new UploadableFile(fileUpload.FileName, text, ".txt"); ;
MultipartWebRequest myRequest = new MultipartWebRequest(APIKEY,token,url);
string response = myRequest.SubmitFiles(files, false, null, new string[] { }, "0");
txtResponse.Text = response;
}
}
As you can see I have tried all of the different upload urls that I have found around the site. And with all the different ones, not sure exactly which one to use, but doc appears to be the latest "most" correct one? Any help with this would be greatly appreciated as I am fairly new (but understand) to post requests in C#, but VERY new (never done one) to multipart forms in C# (or really anywhere).
The current recommended URL for the API (including file uploads) appears to now be https://api.box.com/2.0. Have you tried using that base URL?