I'm trying to update token, but I get error "The remote server returned an error: (400) Bad Request."
My code is:
public static object Refresh_token(string client_id, string redirect_uri, string client_secret, string refresh_token, string scope)
{
var requestUrl = new StringBuilder("https://login.live.com/oauth20_token.srf");
requestUrl.Append("?grant_type=refresh_token");
requestUrl.AppendFormat("&client_id={0}", client_id);
requestUrl.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(redirect_uri));
requestUrl.AppendFormat("&client_secret={0}", HttpUtility.UrlEncode(client_secret));
requestUrl.AppendFormat("&refresh_token={0}", refresh_token);
WebRequest request = HttpWebRequest.Create(requestUrl.ToString());
request.Method = "GET";
request.ContentType = "application/x-www.form-urlencoded;charset=UTF-8";
WebResponse response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<Offline_access>(json);
}
}
If I send it from browser I get
{"error":"invalid_scope","error_description":"The provided request must include a 'scope' input parameter."}
I tried to do it with POST, but it was the same problem.
Have some ideas?
Seems like the spec changed on the web server side and it's expecting you to send a scope parameter. I don't know what the scope parameter is and what you need to supply to it but essentially you'll need to add a line for the requestUrl to add it.
requestUrl.AppendFormat("&scope={0}", {whatever value the scope is suppose to be});
Related
I am playing around with an app using HttpWebRequest to dialog with a web server.
I followed standard instructions I found on the web to build my request function that I tried to make as generic as possible (I try to get a unique method regardless of the method: PUT, POST, DELETE, REPORT, ...)
When I submit a "REPORT" request, I get two access logs on my server:
1) I get response 401 after following line is launched in debugger
reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
2) I get response 207 (multi-get, which is what I expect) after passing the line calling Request.GetResponse();
Actually, it seems to be the Request.GetRequestStream() line that is querying the server the first time, but the request is only committed once passing the reqStream.Write(...) line...
Same for PUT and DELETE, the Request.GetRequestStream() again generates a 401 access log on my server whereas the Request.GetResponse(); returns code 204.
I don't understand why for a unique request I have two server access logs, especially one that seems to be doing nothing as it always returns code 401... Could anybody explain what is going on? Is it a flaw in my code or a bad design due to my attempt to get a generic code for multiple methods?
Here is my full code:
public static HttpWebResponse getHttpWebRequest(string url, string usrname, string pwd, string method, string contentType,
string[] headers, string body) {
// Variables.
HttpWebRequest Request;
HttpWebResponse Response;
//
string strSrcURI = url.Trim();
string strBody = body.Trim();
try {
// Create the HttpWebRequest object.
Request = (HttpWebRequest)HttpWebRequest.Create(strSrcURI);
// Add the network credentials to the request.
Request.Credentials = new NetworkCredential(usrname.Trim(), pwd);
// Specify the method.
Request.Method = method.Trim();
// request headers
foreach (string s in headers) {
Request.Headers.Add(s);
}
// Set the content type header.
Request.ContentType = contentType.Trim();
// set the body of the request...
Request.ContentLength = body.Length;
using (Stream reqStream = Request.GetRequestStream()) {
// Write the string to the destination as a text file.
reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
reqStream.Close();
}
// Send the method request and get the response from the server.
Response = (HttpWebResponse)Request.GetResponse();
// return the response to be handled by calling method...
return Response;
}
catch (Exception e) {
throw new Exception("Web API error: " + e.Message, e);
}
I'm trying to implement the OAuth using a simple class but I'm getting an error
public OAuthResponse AcquireRequestToken(string uri, string method)
{
NewRequest();
var authzHeader = GetAuthorizationHeader(uri, method);
// prepare the token request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Headers.Add("User-Agent", "MyAppId/1.0.3 +http://example.pt/");
request.Headers.Add("Authorization", authzHeader);
request.Method = method;
request.ContentLength = 0;
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
var r = new OAuthResponse(reader.ReadToEnd());
this["token"] = r["oauth_token"];
// Sometimes the request_token URL gives us an access token,
// with no user interaction required. Eg, when prior approval
// has already been granted.
try
{
if (r["oauth_token_secret"] != null)
this["token_secret"] = r["oauth_token_secret"];
}
catch { }
return r;
}
}
}
The error it's in this line
var response = (System.Net.HttpWebResponse)request.GetResponse()
and the error is
Aditional information: The remote server returned an error: (403)
Forbidden.
Any Help? Here is the full OAuth class https://cropperplugins.codeplex.com/SourceControl/changeset/view/65377#1710422
Also the service that i'm trying to access it's Discogs.com API DOCS: http://www.discogs.com/developers
UPDATE 1
I've added the user-agent header the discogs Staff said it was needed but now I have another error on the User-Agent line request.Headers.Add("User-Agent", "BandFollowerWD/1.0.3 +http://pcdev.pt/");
The 'User-Agent' header must be modified with the appropriate property or method.
After searching furder more I've found the answer....
Instead of using request.Headers.Add("User-Agent", "MyAppId/1.0.3 +http://example.pt"); I've used request.UserAgent = "MyAppId/1.0.3 +http://example.pt";
I am trying write simple request to REST service.Follow to documentation from REST Service provider:
I should use in header Content-Type: application/json.
Response return in json format
For authorization proccess I have to send two headers one with APIKey and second with APISign
Controller PING in REST service to test code.
I use .net 2.0
string sha1String = APIKey + "/rest/ping" + APISecret;
string XRestApiSign = SHA1HashStringForUTF8String(sha1String);
string data = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restServer);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-Rest-ApiSign", XRestApiSign);
request.Headers.Add("X-Rest-ApiKey", APIKey);
request.ContentLength = data.Length;
StreamWriter requestWriter;
Stream webStream = request.GetRequestStream();
using (requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) ;
{
requestWriter.Write(data);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
List<string> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(response.GetResponseStream().ToString());
}
}, null);
I should get response string PONG but I get below message
Unexpected character encountered while parsing value: S. Path '', line 0, position 0
Is code OK ? Why I get this message?
This is mostly the case because the script that generates the JSON on the server side adds the byte order mark to the response.
In your case, however, you're trying to convert the stream to JSON, not the content of the stream. You need to read all text from the stream and deserialize the object from that. You need to call one of the methods on the stream that reads the content.
I modified my code with yours suggestion and it works. Now I have problem with send data :)
Subscription user1 = new Subscription
{
Email = "kubaIt#test.com.pl",
List = "xfct2bjcdv",
};
List<Subscription> user = new List<Subscription>();
user.Add(user1);
string json = JsonConvert.SerializeObject(user);
string data = json;
I added above. Other code is the same. I got error :The request was aborted: The request was canceled."
json = [{\"email\":\"kubaIt#test.com.pl\",\"list\":\"xfct2bjcdv\"}] //value from debuger
Attempting to retrieve quota information from Google Drive via REST in C#. Here is a code snippet:
public async Task<string> HasQuota(string accessToken) {
var url = string.Concat(new string[] {
" https://www.googleapis.com/drive/v2/about",
"?access_token=" + accessToken,
"&fields=quotaBytesTotal%2CquotaBytesUsed"
});
// Create the request.
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
// Create the response.
var response = await Task<WebResponse>.Factory.FromAsync(
request.BeginGetResponse,
request.EndGetResponse,
request
);
if (((HttpWebResponse)response).StatusDescription == "OK") {
using (Stream stream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
return null;
}
When I obtained the access_token I scoped the authentication request with https://www.googleapis.com/auth/drive.file and my test user granted permissions. So as far as I aware I have the code requirements to execute this call.
However I get an NotFound exception when I attempt to execute this method. The documentation says I can pass the access_token in the query string or add the Authorization header to the request i.e
request.Headers["Authorization"] = string.Format("Bearer {0}", accessToken);
Any ideas why I might be getting this exception?
Thanks
I hadn't enabled the Drive API option in the console...
I'm Trying to access Google Data (Contact, Edit profile data, Calendar ... etc) by using GData and OAuth2.0 server side (Check this link), I finished the first step and got the first code, and when try to post a request to get the oauth2_token I always got the error "The remote server returned an error: (400) Bad Request."
Here is the code I use to POST the request that returns the OAuth2_token:
string clientToken = Request.QueryString["code"];
string post =
string.Format(
#"code={0}&client_id={1}&client_secret={2}&redirect_uri=http://localhost/default.aspx&grant_type=authorization_code",
clientToken, Settings.ClientId, Settings.ClientSecret);
WebRequest httpRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
StreamWriter streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(post);
streamWriter.Flush();
streamWriter.Close();
var ss = (HttpWebResponse)httpRequest.GetResponse();
Stream stream = ss.GetResponseStream();
Any help??? I spent 2 days till now trying to solve it but in vain :(
could it be that the redirect_uri needs to be URI encoded?
[https://groups.google.com/forum/#!topic/oauth2-dev/9xnn8nUIA2s]
I think you should encode the redirect_uri parameter using HttpUtility.UrlEncode.
also, you should encode the request body using Utf8 encoding:
byte[] encoded = Encoding.UTF8.GetBytes(post);
httpRequest.ContentLength = encoded.Length
hope this helps.