Google Play Music Api Unauthorized Response - c#

First up I am aware that the api is not supported.
https://stackoverflow.com/questions/16707164/is-there-a-google-play-music-api
I have been attempting to reverse engineer some of the apis in the above post. These have been the only real source of information as no where else documents it.
I have successfully been able to implement a oauth token retrieval system.
However when I pass my token To the following I get Forbidden Error 403
Url =
https://play.google.com/music/services/streamingloadalltracks?format=jsarray
Headers =
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
Code
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(paramObj.Base);
client.Timeout = TimeSpan.FromSeconds(5);
if (!paramObj.skipAuth)
{
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
}
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("sdch"));
try
{
if (paramObj.post)
{
return client
.PostAsync(paramObj.method + paramObj.queryString, paramObj.content)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
else
{
return client
.GetAsync(paramObj.method + paramObj.queryString)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
}
catch (Exception exception)
{
return null;
}
}
Question is why isnt this working. I have been looking into the other apis and they implement the same calls(i think my python is pretty rusty)
Token Generator.
public string Oauth2AuthorizeUrl =>
string.Format(
"{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}&access_type=offline",
GooglePlayAuthorizeMethod,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
GooglePlayAuthorizeScope
);
public void Oauth2RetrieveToken(string code)
{
var querystring = string.Format(
"?response_type=code&code={0}client_id={1}&client_secret={3}&redirect_uri={2}&grant_type=authorization_code",
code,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
ClientSecret
);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://accounts.google.com");
client.Timeout = TimeSpan.FromSeconds(5);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id", ClientId),
new KeyValuePair<string, string>("client_secret", ClientSecret),
new KeyValuePair<string, string>("redirect_uri", GooglePlayAuthorizeRedirectURL),
new KeyValuePair<string, string>("grant_type", "authorization_code")
});
var result = client
.PostAsync(GooglePlayRequestToken , content)
.Result
.Content
.ReadAsStringAsync()
.Result;
var value = JObject.Parse(result);
var libs = User.Libs;
libs.GooglePlayPassword = value["access_token"].ToString();
User.UpdateSettings(libs);
}
}

Check out my attempt of an google play music API here (https://github.com/coman3/Google.Music)).
It's working perfectly when it comes to authentication and calls (although does not support 2 factor auth).

Related

API request WaitingForActivation "Not yet computed" error via asp.net

this is my code via asp.net web form:
public string GetAccessToken()
{
ServicePointManager.Expect100Continue=true;
string accessToken = "";
System.Net.ServicePointManager.SecurityProtocol=System.Net.SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
var clientId = "<"+PAYPAL_CLIENT_ID+">";
var clientSecret = "<"+PAYPAL_SECRET_KEY+">";
var bytes = Encoding.UTF8.GetBytes(clientId+":"+clientSecret);
client.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
var responseMessage = client.PostAsync("https://api.sandbox.paypal.com/v1/oauth2/token", new FormUrlEncodedContent(keyValues));
accessToken= responseMessage.Status.ToString();
}
return accessToken;
}
But I get this error:
Id = 9, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" in AccessToken
client.PostAsync is an asynchronous method that returns a Task object. You either need to await it (this is the preferred approach), but that would require a change to the signature of the GetAccessToken() function (and probably to the upstream code) or simply do the following:
var responseTask = client.PostAsync("https://api.sandbox.paypal.com/v1/oauth2/token", new FormUrlEncodedContent(keyValues));
responseTask.Wait();
var responseMessage = responseTask.Result;

Uber-API Access_Token in a POST response now seems to be longer than before, how do I retrieve the actual Access_Token out of it using C#?

When trying to get a new access token, using the refresh token from v2, I now receive a very long token that looks like an encrypted key of some sort. Initially, it just used to be a straight forward access_token of almost the same length as the refresh_token. Is this now the new access_token to use going forward when sending an Uber request on behalf of a customer? Or how do I retrieve the actual access_token I should use in my Uber request, i.e. the one that used to be of almost the same length as the refresh token.
Below is a screenshot of the response I get using Postman.
POSTMAN Screenshot
Below is the C# sourcecode snippet method am calling to retrieve the access_token.
public async Task WebServerAsyncRefresh(string clientId, string clientSecret, string redirectUri, string RefreshToken)
{
if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId");
if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret");
if (string.IsNullOrEmpty(redirectUri)) throw new ArgumentNullException("redirectUri");
if (string.IsNullOrEmpty(RefreshToken)) throw new ArgumentNullException("refreshToken");
if (!Common.IsValidUri(redirectUri)) throw new ArgumentException("Invalid redirectUri");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("refresh_token", RefreshToken)
});
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(TokenUrl),
Content = content
};
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
if (responseMessage.IsSuccessStatusCode)
{
var authToken = JsonConvert.DeserializeObject<AuthToken>(response);
AccessToken = authToken.access_token;
RefreshToken = authToken.refresh_token;
}
else
{
//TODO: Create appropriate error response
//var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
//throw new ForceAuthException(errorResponse.error, errorResponse.error_description);
throw new Exception("error");
}
}

Twilio REST Api call bad request

I've implemented Twilio REST API with C# successfully earlier. However, all of a sudden the API calls that are made keep getting 400 - BAD REQUEST.
The response body doesn't contain any specific error either...
I'll say it again, it worked for a week or two and all of sudden it returns BAD REQUEST.
The code is exact the following below.
public async Task SendSmsAsync(string number, string message)
{
var accountSid = _configuration["Authentication:Twilio:AccountSID"];
var authToken = _configuration["Authentication:Twilio:AuthToken"];
var twilioNumber = _configuration["Authentication:Twilio:Number"];
var credentials = new NetworkCredential(accountSid, authToken);
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler))
{
var url = $"https://api.twilio.com/2010-04-01/Accounts/{ accountSid }/Messages";
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("To", number),
new KeyValuePair<string, string>("From", twilioNumber),
new KeyValuePair<string, string>("Body", message),
};
var content = new FormUrlEncodedContent(body);
content.Headers.ContentType.CharSet = "UTF-8";
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
//Uri success = response.Headers.Location;
}
}
}

Using HttpClient in Xamarin PCL to post

I'm trying to make a post to a rest api using HttpClient PCL in Xamarin. I have the following code but I'm getting a 404. Note that I don't have the real ip address here but when I use Hurl.It with the real one it connects just fine, but here just a 404. What am I missing?
string url = "http://myaddresshere/services/rest/auth/login";
string result = String.Empty;
using (var client = new HttpClient()) {
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>(txtUsername.Text, "username"),
new KeyValuePair<string, string>(txtPassword.Text, "password")
});
using (var response = await client.PostAsync(url, content)) {
using (var responseContent = response.Content) {
result = await responseContent.ReadAsStringAsync();
}
}
}
You should probably switch in your code:
new KeyValuePair<string, string>(txtUsername.Text, "username"),
new KeyValuePair<string, string>(txtPassword.Text, "password")
To:
new KeyValuePair<string, string>("username", txtUsername.Text),
new KeyValuePair<string, string>("password", txtPassword.Text)

Trying to login instagram in c# using HttpClient

I'm trying to login to instagram using httpclient library. I'm able to get and post request but everytime i recieve 403 Forbidden status.
initially i'm making a get request to get csrfmiddlewaretoken unique token which instagram uses for cross site request forgery by below code
HttpClient httpClient = new HttpClient();
string CSRFtoken = "";
try
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri("https://instagram.com"), new Cookie("csrfmiddlewaretoken", CSRFtoken));
string pagedata = await httpClient.GetStringAsync(loginURL);
string pattern = #"csrfmiddlewaretoken""\svalue=""(.+)""";
var r = new System.Text.RegularExpressions.Regex(pattern);
var m = r.Match(pagedata);
CSRFtoken = m.Groups[1].Value;
}catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
after that i'm making a post request by sending csfrtoken, username and password
by
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("csrfmiddlewaretoken", CSRFtoken));
postData.Add(new KeyValuePair<string, string>("username", "abcdefg"));
postData.Add(new KeyValuePair<string, string>("password", "1234567"));
HttpClient client = new HttpClient();
try
{
HttpResponseMessage response = await client.PostAsync(loginURL, new FormUrlEncodedContent(postData));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString);
}catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I've read answers here and on msdn site but didn't got any working results.
tried this solution as well Link

Categories