Authentication in wp8 - c#

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);

Related

C# POST/GET Issue with Login Credentials

Pretty much a noob here, having issues here with a Post Request in C#. I am returning the server response to webBrowser Control, and no matter what I try, I just get the login page returned with no form values posted. Any help here would be greatly appreciated!
Login Page: "https://www.carrier411.com/".
URL example that I want to return:(You have to be logged in to view)
"https://www.carrier411.com/manager/companydetail.cfm?docket=MC1114638"
var username = "******"; var password = "******";
string url = "https://www.carrier411.com/manager/companydetail.cfm?docket=MC1073504";
string postData = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + passWord));
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "text/html";
httpRequest.Headers.Add("Authorization", "Basic " + postData);
httpRequest.Accept = #"text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{streamWriter.Write(postData);}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
string result = streamReader.ReadToEnd().ToString();
webBrowser1.DocumentText = result;

how to send token to url in c# windows application

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

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);

Send login details with HttpWebRequest

I'm trying to get this bit of code to pause/unpause my XBMC Player
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl+playPause);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
Debug.WriteLine(resStream);
And I need to send my login data with it, lets say its MyUsername and SuperPassword.
How would I add that data intp the request? I tried request.Headers.Add("Authorization", "MyUsername SuperPassword"); but I still get the 401 error from it.
EDIT: Nevermind, i figured it out
String username = "MyUsername";
String password = "SuperPassword";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
There is a awesome post about Send login details with HttpWebRequest and the link is post link
if You feel brother then you can also try one my Best solve this by using webClient class. example:
var url = #"...";
var mybar= new System.Collections.Specialized.NameValueCollection();
mybar.Add("username", "username");
mybar.Add("password", "password");
var client = new System.Net.WebClient();
var data = client.UploadValues(url, mybar);
var res = System.Text.Encoding.ASCII.GetString(data);
Console.WriteLine(res);
Console.ReadLine();

FileNet P8 workplace token issue

I am trying to get user token and build the URL so that user need not login everytime they click the file. below is my code.
My question is do I need to pass whole of the token value shown below or??
The token value I am getting is
symmetric:algorithm:QUVT:keyid:NTZkYTNkNmI=:data:7P9aJHzkfGTOlwtotuWGaMqfU9COECscA9yxMdK64ZLa298A3tsGlHKHDFp0cH+gn/SiMrwKfbWNZybPXaltgo5e4H4Ak8KUiCRKWfS68qhmjfw69qPv9ib96vL3TzNORYFpp/hrwvp8aX4CQIZlBA==
The problem is, once i copy the URL and past it in the browser, it is taking me to the login page. Though I am not getting any errors, it should take users directly to the imageviewer but instead it takes me to login page, if I login it is opening the file correctly.
What am I doing wrong?
string text = "";
string userName = "userName";
string pwd = "*****";
fileNetID = "{5FCE7E04-3D74-4A93-AA53-26C12A2FD4FC}";
Uri uri = null;
string workplaceURL = "http://filenet:9081/WorkPlaceXT";
uri = new Uri(workplaceURL + "/setCredentials?op=getUserToken&userId=" + this.encodeLabel(userName) + "&password=" + this.encodeLabel(pwd) + "&verify=true");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(uri);
System.Net.WebResponse webResponse = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
String token = streamReader.ReadToEnd();
string contentURL = string.Empty;
contentURL = workplaceURL + "/getContent?objectType=document&impersonate=true&objectStoreName=OBJECTSTORE&id=" + HttpUtility.UrlEncode(fileNetID);
contentURL += "&ut=" + HttpUtility.UrlEncode(encodeLabel(token));
return contentURL;
Here is my function, you can see the last couple lines how I unroll the token at the end:
public static string getCEUserToken(string baseURL, string uid, string pwd)
{
string UserToken = "";
System.Net.WebRequest request = System.Net.WebRequest.Create(baseURL + "/setCredentials?op=getUserToken&userId=" + uid + "&password=" + pwd +
"&verify=true");
request.Method = "POST";
System.Net.WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
byte[] token = new byte[response.ContentLength];
stream.Read(token, 0, (int)response.ContentLength);
response.Close();
foreach (byte chr in token)
UserToken += System.Convert.ToChar(chr);
return System.Web.HttpUtility.UrlEncode(UserToken);
}

Categories