how to send token to url in c# windows application - c#

using System.Net.WebClient and DownloadString the URL contents gives me a token. the server uses this token as "https://address/page?token=AAABBBXXX".
by using this code
string contents;
string token;
string url = #"https://address/login";
var wc = new System.Net.WebClient();
contents = wc.DownloadString(url);
token = contents.Substring(contents.IndexOf("page.public.pageToken = '") + "page.public.pageToken = '".Length, 32);
url = "https://address/page?token=" + token;
**contents = wc.DownloadString(url);** //error error error !!!!
I can get token value from page content but how to send this token and validate my request? last line causes server error timeout! shall I save token value in any session? how do it in windows application?

using(WebClient wc = new WebClient()
{
string WebURL = #"http://www.mywebsite.com/somefolder/somepage";
NameValueCollection param = new NameValueCollection()
{
{ "token", "abcdefghijklmnopqrstuvwxyz01234567890" }
};
object WebResponse = Encoding.UTF8.GetString(wc.UploadValues(WebURL, "GET", param));
}
correct me if i am wrong, but you said "send", which might be equal to "upload".
that above code would be equal to a browser processing a link # http://www.mywebsite.com/somefolder/somepage?token=abcdefghijklmnopqrstuvwxyz01234567890

Related

Get Gmail Inbox feed Google.Apis C# .NET

I need to read the gmail inbox feed using Oauth2.0. Simulating in the postman,
Auth URL : https://accounts.google.com/o/oauth2/auth
Access Token URL : https://accounts.google.com/o/oauth2/token
Client ID : XXXXX.apps.googleusercontent.com
Client Secret : XXXXX
Scope : https://mail.google.com/mail/feed/atom
GrantType: Authorization Code
I requested the token and used it on the header
Authorization - Bearer XXXXXXXXXX.
And I made the request via GET right in my scope and got my email feeds. Works!!!
The postman generates a code in C #, but the token expires.
var client = new RestClient("https://mail.google.com/mail/feed/atom/");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "d48cac24-bd3e-07b5-c616-XXXXXXXX");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer ya29.a0AfH6SMDZlUmw0xLHAoYIJuIfTkXXXXXXXXQSPP17GmXT26fJEfWB9w8UiwQ2YF32-nOp6zY9H_lwJEEXXXXXXXXXXXYK4e0tcZkieGbBl5Eow2M-7Gxp20kfDtXXXXXVjiXymLXyMkYEI");
IRestResponse response = client.Execute(request);
I'm trying to do it via Google.Api, using GoogleAuthorizationCodeFlow and already using token refresh.
With the code below, I got authorization from the application, but I can't read the xml atom feed
GoogleAuthorizationCodeFlow flow;
var assembly = Assembly.GetExecutingAssembly();
var clientfile = #"client_secrets.json";
using (var stream = new FileStream(clientfile, FileMode.Open, FileAccess.Read))
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("StoreTest"),
ClientSecretsStream = stream,
Scopes = new[] { "https://mail.google.com/mail/feed/atom/" }
});
}
var uri = Request.Url.ToString();
var code = Request["code"];
if (code != null)
{
var token = flow.ExchangeCodeForTokenAsync(UserId, code,
uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
// Extract the right state.
var oauthState = AuthWebUtility.ExtracRedirectFromState(
flow.DataStore, UserId, Request["state"]).Result;
Response.Redirect(oauthState);
}
else
{
var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
CancellationToken.None).Result;
if (result.RedirectUri != null)
{
// Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri);
}
else
{
// The data store contains the user credential, so the user has been already authenticated.
var gmailfeed = new GmailService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "GetFeed",
});
var inboxlistRequest = gmailfeed.Users.Messages.List("me");
inboxlistRequest.LabelIds = "Label_19780355190759038";
inboxlistRequest.IncludeSpamTrash = false;
var emailListResponse = inboxlistRequest.Execute();
foreach (var mail in emailListResponse.Messages)
{
var mailId = mail.Id;
var threadId = mail.ThreadId;
Message message = gmailfeed.Users.Messages.Get("me", mailId).Execute();
Console.WriteLine((message.Snippet));
}
}
}
I got to read the email, but I need the xml atom feed.
Could someone help me how I make this call to get the atom feed, using the granted token. If there is an easier way to do it too, it would be cool to share.
Thank you
Resolved using respsharp, restclient!!
tks

How to get an access token from ebay via OAuth 2.0

This is less a question than an answer. I figured I would want to share this with you, since I was a bit confused finding so litte about the ebay OAuth 2.0 in combination with a C# web application.
I tried starting to use the RESTsharp library, but got stuck at the point, where the body content was created. RESTsharp prefers XML or JSON, ebay want's a string with params.
So to give you all a little help if you run into the same issue, I decided to post my solution (not using RESTsharp).
public class HomeController : Controller {
string clientId = "YOUR_CLIENT_ID";
string clientSecret = "YOUR_CLIENT_SECRET";
string ruName = "YOUR_RU_NAME";
// Redirect the request to get a request token
public ActionResult Index() {
var authorizationUrl =
"https://signin.sandbox.ebay.de/authorize?" +
"client_id=" + clientId + "&" +
"redirect_uri=" + ruName + "&" +
"response_type=code";
Response.Redirect(authorizationUrl);
return View();
}
// I used Test as a method to test the result in the controller, use your apropriate method here
public ActionResult Test(string code)
{
ViewBag.Code = code;
// Base 64 encode client Id and client secret
var clientString = clientId + ":" + clientSecret;
byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);
HttpWebRequest request = WebRequest.Create("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add(HttpRequestHeader.Authorization, credentials);
var codeEncoded = HttpUtility.UrlEncode(code);
var body = "grant_type=authorization_code&code=" + codeEncoded + "&redirect_uri=" + ruName;
// Encode the parameters as form data
byte[] formData = UTF8Encoding.UTF8.GetBytes(body);
request.ContentLength = formData.Length;
// Send the request
using (Stream post = request.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
// Pick up the response
string result = null;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
ViewBag.Response = result;
return View();
}
If you output ViewBag.Response you will see the authorization code. Have fun.
How is your redirect url looking in sandbox? Seems like the url should be https. In this stage in dev environment and don't have server with https. How did you deal with that?
Ta

500 px api with C# throwing 500 Internal Server Error

I am trying to implement 500px API with C#. I am able to authenticate user with 500px API but I am unable to get the access_token in exchange of response_token which leaves my third step of Oauth 1.0 incomplete. I am able to authorize user and get oauth_token and oauth_verifier but when I use this oauth_token for making following request :-
https://api.500px.com/v1/oauth/access_token
500 Internal Server Error along with the following screen gets thrown
I have debugged my code like thousand times, tried different ways to form URL, added various parameters to the request but no help. I am very badly stuck as almost no information is available on 500px developer website or on web for using this api in C#. I have reached a dead-end!
Following is my code:-
1.]For requesting token and authorizing user :-
string normalizedUrl;
string normalizedRequestParameters;
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
Uri uri = new Uri("https://api.500px.com/v1/oauth/request_token");
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
string timeStamp = myOAuth.GenerateTimeStamp();
string nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
string signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret,
"", "", "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
string authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl = new Uri(authorizationUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(signInUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stIn = new StreamReader(response.GetResponseStream());
string responseString = stIn.ReadToEnd();
stIn.Close();
//oauth_token=cf40227bb7ede4d6e56ff790324761b3&oauth_token_secret=0bcb59dff2c1d095739c86c534fc62d7ed224fecfe8744d48c9c95f36211382f
if (responseString.Contains("oauth_token=") && responseString.Contains("oauth_token_secret="))
{
String RespToken = responseString.Split('&')[0].Replace("oauth_token=", "");
String RespSecret = responseString.Split('&')[1].Replace("oauth_token_secret=", "");
uri = new Uri("https://api.500px.com/v1/oauth/authorize");
timeStamp = myOAuth.GenerateTimeStamp();
nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret, RespToken
, RespSecret, "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
Console.WriteLine("Signature=="+signature);
authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl1 = new Uri(authorizationUrl);
webBrowser1.Navigate(signInUrl1);
}
2.]After User clicks on Authorise this application for getting access_token:-
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string parameters;
string normalizedUrl;
string normalizedRequestParameters;
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
if (e.Url.ToString().Contains("https://www.xyz.com/"))
{
String url = (e.Url.ToString()).Replace("https://www.xyz.com/?","");
if( url.Contains("oauth_token="))
{
string OAuthToken = url.Split('&')[0].Replace("oauth_token=", "");
var uri = "https://api.500px.com/v1/oauth/access_token";
OAuthBase oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timeStamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(new Uri(uri), consumerKey, consumerSecret,
OAuthToken, String.Empty, "POST", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
signature = HttpUtility.UrlEncode(signature);
var requestUri = normalizedUrl + "?" + "oauth_callback=https://www.xyz.com" +"?"+ normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Console.WriteLine(requestUri);
var request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
// request.ContentType = "application / x - www - form - urlencoded";
//request.Credentials = CredentialCache.DefaultCredentials;
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();
}
}
catch(Exception ex)
{
Console.Writeln(ex.toString());
}
}
Now following is the line where my code is breaking:-
var response = request.GetResponse();
Completely at my wits end on this issue, not able to get to the root of it. Any help any directions will be highly appreciated. Any suggestions would be of great help!!
Thanks a ton in advance!
Here's what to do:
Use GET rather than POST (POST may work; I've not tried it and have had little success with 500px and POSTing)
Include the oauth_verifier you received during the authorisation step in the query URL
Sign the entire query using your consumer key and request token secret (returned in step 1)
Code snippet which should return "oauth_token=...&oauth_token_secret=..." in the HTTP reply body.
Make sure your OAuth implementation doesn't strip out any parameters beginning with "oauth_"! Mine was and it was stripping out the oauth_verifier parameter which is required by 500px.
OAuth.OAuthBase oauth = new OAuth.OAuthBase();
string strUrl = "";
string strParams = "";
string signature = oauth.GenerateSignature(new Uri(API_URL + "oauth/access_token?oauth_verifier=" + this.oauthVerifier),
this.consumerKey, this.consumerSecret, this.oauthToken, this.requestTokenSecret,
"GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(),
OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out strUrl, out strParams);
string authorizationUrl = strUrl + "?" + strParams + "&oauth_signature=" + System.Web.HttpUtility.UrlEncode(signature);
Debug.WriteLine("url>" + authorizationUrl);
Response reply = SendGetRequest(authorizationUrl);
if (reply.Success)
{
Debug.WriteLine("access_token>" + reply.Content);

Authentication in wp8

I'm developing WP8 application. I need to add data in the url by using the E-mail id and password. I am using webclient(), but I don't know how to do it. Can anyone help me to complete the task?
Thanks in advance.
My URL format:
http://xx.xx.xxx.xxx/main/content/api/data/pagename?email=abcd#abcd.com&sig=abcd
This is my url structure. I need to add data for the user above.
My Form Design:
![enter image description here][1]
When I click the log-in button I should verify the emailid and password from the above mentioned url structure.
The code below works for posting the data, but I need to know how to post the data by using email and password.
public T Post<T>(string servicePath, string result)
{
string serviceURL = REST_URI + servicePath;
Uri URI = new Uri(serviceURL);
System.Net.WebClient webClient = new WebClient();
webClient.Headers["ContentType"] = "application/json";
webClient.Headers["Accept"] = "application/json";
webClient.UploadStringCompleted += this.sendPostCompleted;
webClient.UploadStringAsync(URI, HTTP_POST, result);
return default(T);
}
Try this , here I'm retrieving username and password from text box,
var username = uname.Text;
var password = pass.Password;
var postData = "email=" + username + "&password=" + password;
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
var uri = new Uri("Your URL here", UriKind.Absolute);
webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.UploadStringAsync(uri, "POST", postData);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postComplete);

In Facebook integration I have to access the url of in which access token is given, but instead I am getting my published url in asp.net

I am using the following code on Page_Load of facebook_login page in asp.net web application. After redirecting this url I have got the accesstoken in url but when I try to access this current url via HttpContext.Current.Request.Url.AbsoluteUri it gave the url of app where it is published not the url which is currently in window.
How can I access this access token or userdetails?
var uriParams = new Dictionary<string, string>() {
{"client_id", facebookAppId},
{"response_type", "token"},
{"scope", "user_about_me, read_stream, email"},
{"redirect_uri", "http://apps.facebook.com/appNameHere/"}
};
StringBuilder urlBuilder = new StringBuilder();
foreach (var current in uriParams)
{
if (urlBuilder.Length > 0)
{
urlBuilder.Append("&");
}
var encoded = HttpUtility.UrlEncode(current.Value);
urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
}
var loginUrl = "http://www.facebook.com/dialog/oauth?" + urlBuilder.ToString();
Response.Redirect(loginUrl);
In Facebook you can set call back url value which should point to your web application. So once you make request to http://www.facebook.com/dialog/oauth and after successfully login Facebook redirect to Callback Url (which is your web application).
Then you have to make call to url : https://graph.facebook.com/oauth/access_token something like this:
StringBuilder uri = new StringBuilder();
uri.Append("https://graph.facebook.com/oauth/access_token?");
uri.Append("client_id=" + ClientKey + "&");
uri.Append("redirect_uri=" + Curl + "&");
uri.Append("scope=offline_access&");
uri.Append("client_secret=" + ClientSecret + "&");
uri.Append("code=" + OAuthCode);
HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization", String.Empty);
req.Method = "POST";
req.ServicePoint.Expect100Continue = false;
req.ContentLength = 0;
req.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd().Trim();
string[] resultCollection = Regex.Split(result, "&");
string access_token = Regex.Split(resultCollection[0], "=")[1];//This is the access token
//which you want and you can save it to database or some where for further use.
}
catch (WebException ex)
{
resp = (HttpWebResponse)ex.Response;
//pass on the exception
throw ex;
}
UPDATE :
OAuthCode you can get like this, it is available when after successfully login FB redirect to your web app page
OAuthCode = Request.Params["code"];
Header you can pass empty like String.Empty

Categories