Implementing Last.fm authentication in Windows Phone 8 - c#

I need to implement last.fm authentication in my Windows Phone 8 application. Last.fm requires a POST request with https for successful login. Here is what I'm doing.
public async void GetMobileSession(string userName, string password, Action<LastFmAuthResponse> onCompletion)
{
string CORE_URL = "https://ws.audioscrobbler.com/2.0/";
var parameters = new Dictionary<string, string>();
parameters.Add("username", userName);
parameters.Add("password", password);
parameters.Add("method", "auth.getMobileSession");
parameters.Add("api_key", api_key);
string signature = GetSignature(parameters);
string comboUrl = string.Concat("method=auth.getMobileSession", "&api_key=", api_key,
"&username=", userName, "&password=", password, "&api_sig=", signature);
LastFmAuthResponse response = null;
byte[] pendingPostContent = Encoding.UTF8.GetBytes(comboUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(CORE_URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(pendingPostContent, 0, pendingPostContent.Length);
}
request.BeginGetResponse(new AsyncCallback(n =>
{
HttpWebResponse rawResponse = (HttpWebResponse)request.EndGetResponse(n);
string rawData = string.Empty;
using (StreamReader reader = new StreamReader(rawResponse.GetResponseStream()))
{
rawData = reader.ReadToEnd();
}
try
{
if (!string.IsNullOrEmpty(rawData))
{
response = CommonFunctions.GetObjectFromString<LastFmAuthResponse>(rawData);
}
}
catch
{
}
onCompletion(response);
}), null);
}
However the code is failing at request.BeginGetResponse It returns an error saying remote server could not be found. Can someone please point out what I'm doing wrong here?

Related

.net core call REST API on my localhost to get token - getting badRequest

I have 2 programs on my localhost, one with REST API and another program that calls the api.
I'm trying to authenticate user(https://localhost:44301/token) with below function and getting badRequest.
the same is working when testing with postman.
baseUrl is "https://localhost:44301/";
static async Task<Uri> AddCartRecordAsync(CartsTable cartsTable)
{
string ResponseString = "";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(Utility.baseUrl + "token");
request.Accept = "application/json";
request.Method = "POST";
//Get credentials from config.
var username = "kkk#gmail.com";
var password = "Test123!";
Credentials cred = new Credentials()
{
username = username,
password = password,
grant_type = "password"
};
var myContent = JsonConvert.SerializeObject(cred);
var data = Encoding.ASCII.GetBytes(myContent);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
using (response = (HttpWebResponse)request.GetResponse())//BadRequest Here
{
ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
catch (Exception e)
{
string i = "df";
}
The common issues are :
1-Params Body Type
2-Authentication Type : if u have bearer type you should include bearer keyword before your token in the header before sending request like "token":"bearer AuthToken"
3-method type : get put post delete

C# Credential validation against Jira using the REST API

I'm working on a C# Windows Form application and I would like to have the ability to test a users' credentials against Jira. Basically the user would input their username and password, click OK and the program will tell them if their credentials are accepted or not.
I already have working code (see below) that uses basic authentication via HttpWebRequest to create new tickets (aka issues), close tickets, add watchers, etc - so I figured this would be easy but I'm struggling with it.
As an analog, you can do a credentials check against Active Directory very easily using the System.DirectoryServices.AccountManagement namespace. Basically the method authenticateAD() will simply return true or false:
private bool authenticateAD(string username, string password)
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "example.com");
bool isValid = pc.ValidateCredentials(username,password);
return isValid;
}
This is exactly the kind of thing I want to do with Jira.
For reference, here's the code I'm using to add/close/update tickets in jira - maybe it can be modified to do what I want?
private Dictionary<string, string> sendHTTPtoREST(string json, string restURL)
{
HttpWebRequest request = WebRequest.Create(restURL) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
string mergedCreds = string.Format("{0}:{1}", username, password);
byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
request.Headers.Add("Authorization", "Basic " + byteCreds);
byte[] data = Encoding.UTF8.GetBytes(json);
try
{
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
}
catch(Exception ex)
{
displayMessages(string.Format("Error creating Jira: {0}",ex.Message.ToString()), "red", "white");
Dictionary<string, string> excepHTTP = new Dictionary<string, string>();
excepHTTP.Add("error", ex.Message.ToString());
return excepHTTP;
}
response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var sData = jss.Deserialize<Dictionary<string, string>>(str);
if(response.StatusCode.ToString()=="NoContent")
{
sData.Add("code", "NoContent");
request.Abort();
return sData;
}
else
{
sData.Add("code", response.StatusCode.ToString());
request.Abort();
return sData;
}
}
Thanks!
How about attempting to access the root page of JIRA and see if you get an HTTP 403 error?
try
{
// access JIRA using (parts of) your existing code
}
catch (WebException we)
{
var response = we.Response as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.Forbidden)
{
// JIRA doesn't like your credentials
}
}
The HttpClient would be simple and best to use check credentials with GetAsync.
The sample code is below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(JiraPath);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string mergedCreds = string.Format("{0}:{1}", username, password);
byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
var authHeader = new AuthenticationHeaderValue("Basic", byteCreds);
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage response = client.GetAsync(restURL).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
strJSON = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(strJSON))
return strJSON;
}
else
{
exceptionOccured = true;
// Use "response.ReasonPhrase" to return error message
}
}

Get Access Token Using C#, Windows phone 8.1

I am trying to get the access token for the feed.Below is a code, i used to get the access token.
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
string url = "http://example.net/Token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
try
{
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();//parse token from result
}
catch(Exception ex)
{
}
return "";
}
The error below
"An error occurred while sending the request. The text associated with this error code could not be found.
The server name or address could not be resolved"
is throwing while it executes the below code
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Please help me to solve the issue
Try this if you are using POST request
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
try
{
using (var httpClient = new HttpClient())
{
var request1 = new HttpRequestMessage(HttpMethod.Post, "FeedURL");
request1.Content = new StringContent(postString);
var response = await httpClient.SendAsync(request1);
var result1 = await response.Content.ReadAsStringAsync();
result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
var rootObject1 = JObject.Parse(result1);
string accessToken = rootObject1["access_token"].ToString();
}
}
catch (Exception ex)
{
}
}

Unable to get Refresh Token in Google Calendar Version 3

I am developing my for Google Integration in ASP.NET. I am tring to create a service using access token and refresh token. But i am unable to get the refresh token as i am just getting Access Token, Token Type and Expires in. Please check the below code for this.
private String ExchangeCodeWithAccessAndRefreshToken()
{
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(Convert.ToString(Session["URL"]));
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}";
string Code = Request.QueryString["Code"];
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
String ClientID = ConfigurationManager.AppSettings["clientID"].ToString();
String ClientSecret = ConfigurationManager.AppSettings["clientSecret"].ToString();
string param = string.Format(data, Code, ClientID, ClientSecret, redirect_uri_encode, grant_type);
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();
}
var jsonSerializer = new JavaScriptSerializer();
var tokenData = jsonSerializer.Deserialize<GoogleTokenModel>(result);
return tokenData.Access_Token;
}
Try setting access_type=offline in your URL:
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type=offline";

How to pass data in web services?

I want to pass data user Id and user code to another server and get the response using network.
So, I created this code
var webRequest = WebRequest.Create(#"http://10.2.1.85/");
It is working fine but I don't know how to pass the user Id and user code.
Do I have to create object or something?
How can I do it?
This is how to Post Data on Web Service:
WebService Post Function
public static string JsonPost(string url, string method, string postData)
{
Uri address = new Uri(url + method);
//Get User current network credential
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(address, "Basic");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
//Network Credential should be included on the request to avoid network issues when requesting to the web service
request.Proxy = WebRequest.DefaultWebProxy;
request.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
request.Proxy.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string JsonResponse = reader.ReadToEnd();
return JsonResponse;
}
}
Login Function
public static string Login(string Email, string Password)
{
try
{
string postData = "{" + "\"Email\":\"" + Email + "\"," +
"\"Password\":\"" + Password + "\"" +
"}";
string JsonResult = JsonPost("Your Web Service URL", "Login", postData);
return JsonResult;
}
catch (Exception ex)
{
return "";
}
}
Example How To Use:
public void LoginUser()
{
string Email = "me#example.com";
string Password = "password";
string JsonUserAccount = Login(Email, Password);
if(!string.IsNullOrEmpty(JsonUserAccount))
{
Debug.Print("User logged in");
}
else
{
Debug.Print("Failed to logged in");
}
}

Categories

Resources