Get Access token from Spotify api - spotify

I'm trying to get a access token from this endpoint using asp.net: https://accounts.spotify.com/api/token
The token i get back has Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}".
When creating my app over att Spotify Developer i stated my Redirect Uri as http://localhost:59486/ which is my Project Url.
What am i doing wrong?
I have borrowed this method from https://hendrikbulens.wordpress.com/2015/01/07/c-and-the-spotify-web-api-part-i/
private async Task<string> GetAccessToken()
{
SpotifyToken token = new SpotifyToken();
string postString = string.Format("grant_type=client_credentials");
byte[] byteArray = Encoding.UTF8.GetBytes(postString);
string url = "https://accounts.spotify.com/api/token";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Basic YjlkZj****************************************jQ2YjM3MjE5MDE=");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
token = JsonConvert.DeserializeObject<SpotifyToken>(responseFromServer);
}
}
}
}
return token.access_token;
}
EDIT:
This is my Http request:
spotify.com/api/token HTTP/1.1
Authorization: Basic Yjlk....................5MDE=
Content-Type: application/x-www-form-urlencoded
Host: accounts.spotify.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials

Related

Docusign: Obtain the access token

Ref: https://developers.docusign.com/platform/auth/authcode/authcode-get-token/
I am having an issue on Step 2: Obtain Access Token
I am trying to get an access token. However I am getting the following error:
{
"error": "invalid_grant",
"error_description": "unsupported_grant_type"
}
whether its using c# code or using PostMan I am getting the error above.
In PostMan
URL: https://account-d.docusign.com/oauth/token
Method: Post
Headers
Authorization: BASIC BASE64_COMBINATION_OF_INTEGRATION_AND_SECRET_KEYS
Content_Type: application/json;charset=utf-8
Body: I tried form-data, x.www.form-urlencoded, raw... all are the same
grant_type: authorization_code
code: My_AUTHORIZATION_CODE
I also tried getting the access token in the call back page when I get the Authorization Code.
protected void Page_Load(object sender, EventArgs e)
{
var url = ConfigurationManager.AppSettings["DocuSign.TokenEndPoint"];
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = data.Length;
req.ContentType = "application/json; charset=UTF-8";
UTF8Encoding enc = new UTF8Encoding();
var code64 = Convert.ToBase64String(enc.GetBytes($"{ConfigurationManager.AppSettings["DocuSign.ClientId"]}:{ConfigurationManager.AppSettings["DocuSign.ClientSecret"]}"));
req.Headers.Add("Authorization", "Basic " + code64);
using (Stream ds = req.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = req.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}
Your content_type should be application/x-www-form-urlencoded
the following line was wrong:
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
Changed to
var data = $"grant_type=authorization_code&code={Request.QueryString["Code"]}";
I was missing code=

Microsoft Face Detect API code example Bad Request

I have been trying to solve this bad request error. I am able to make the request call and Azure reports total calls correctly and also reports total errors.
I can not get this code example to work; however if I send this via their online console all is fine:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string data = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
Console.Beep();
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
//string statusURL = HttpContext.Current.Request.Url.Host;
//console.WriteLine("Your Status URL address is :" + statusURL);
HttpResponseMessage response;
// Request body
// byte[] byteData = Encoding.UTF8.GetBytes("{url: https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg}");
byte[] byteData = Encoding.UTF8.
GetBytes("{"+ "url"+":"+"https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg" + "}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}
HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StringContent("{body}",
Encoding.UTF8,
"application/json");
//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}// end of Make request
Your JSON is malformed. Your fields and non-scalar fields must be quoted. You also have some unnecessary code. Here's code that works:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string imageUri = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
string body = "{\"url\":\"" + imageUri + "\"}";
using (var content = new StringContent(body, Encoding.UTF8, "application/json"))
{
await client.PostAsync(uri, content)
.ContinueWith(async responseTask =>
{
var responseBody = await responseTask.Result.Content.ReadAsStringAsync();
Console.WriteLine("Response: {0}", responseBody);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}
}// end of Make request
If you're using Visual Studio, I would recommend the NuGet package as this will handle much of the mundane details for you, including C# types for responses.

Can't delete Azure Storage Table using Azure REST API

I am getting an error "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature."
I followed the authorization tutorial provided by Microsoft, Delete Table, Authentication for the Azure Storage Services.
Am I missing anything?
It seems that you’d like to delete table via rest api.
DELETE https://myaccount.table.core.windows.net/Tables('mytable')
the following sample works fine on my side, please refer to the code to generate the signature.
string StorageAccount = "account name here";
string StorageKey = "account key here";
string tablename = "table name";
string requestMethod = "DELETE";
string mxdate = "";
string storageServiceVersion = "2015-12-11";
protected void Button1_Click(object sender, EventArgs e)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture,
"https://{0}.table.core.windows.net/Tables('{1}')",
StorageAccount, tablename));
req.Method = requestMethod;
//specify request header
string AuthorizationHeader = generateAuthorizationHeader();
req.Headers.Add("Authorization", AuthorizationHeader);
req.Headers.Add("x-ms-date", mxdate);
req.Headers.Add("x-ms-version", storageServiceVersion);
req.ContentType = "application/json";
req.Accept = "application/json;odata=minimalmetadata";
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
}
}
public string generateAuthorizationHeader()
{
mxdate = DateTime.UtcNow.ToString("R");
string canonicalizedResource = $"/{StorageAccount}/Tables('{tablename}')";
string contentType = "application/json";
string stringToSign = $"{requestMethod}\n\n{contentType}\n{mxdate}\n{canonicalizedResource}";
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(StorageKey));
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
String authorization = String.Format("{0} {1}:{2}",
"SharedKey",
StorageAccount,
signature
);
return authorization;
}

Is it possible for a web server to make a HTTPS request to itself?

Imagine you have two applications, A & B, running on the same web server.
You want app A to call a webService on app B over SSL.
Is it possible to do that with an address like https://localhost/appsB/webService1?
How can the SSL handshake be done without a client (like a browser?)
It actually works when using this address http://localhost/appsB/webService1, only not in SSL mode.
However it works as well with HTTPS between the server and a browser when calling https://localhost/appsB/webService1.
Now, the strange thing is that it works sometimes but randomly fails when calling the webService on app B using HTTPS. Using HTTP it always works.
My tests are on IIS7.0 with a valid ssl certificate from Thawte with SSL option not required for app B.
Here is an exemple of my code :
string baseAddress = "http://localhost";
//or string baseAddress = "https://localhost";
var baseUri = new Uri(baseAddress);
//final url for appB
finalUrl = baseAddress + httpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/" + url;
//Add a cookie to retrieve good contexte on appB
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseUri })
{
cookieContainer.Add(baseUri, new Cookie("ASP.NET_SessionId", HttpContext.Current.Session.SessionID));
HttpResponseMessage response = client.GetAsync(finalUrl).Result;
Dictionary<string, dynamic> sData;
if (response.IsSuccessStatusCode)
{
etc, etc..
}
All you have to do is create a https client in server A to talk to talk to itself. Below is my code. In my case, it is a client in server A that talks to a webserver interface on Server A. In this case, I am measuring my servers latency performance.
// Get Administration Server Status
public String adminServerStatus() {
uri = "https://" + "localhost" + ":" + adminserverport + "/home";
result = "grn";
adminlatency = 0;
// Build httpHeader entity
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> httpentity = new HttpEntity<String>(headers);
try {
// Build the httpClient
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
// Build httpClient template
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate template = new RestTemplate(requestFactory);
// Now go fire client status request & get latency duration
timenow = System.currentTimeMillis();
ResponseEntity<String> httpresult = template.exchange(uri, HttpMethod.GET, httpentity, String.class);
adminlatency = System.currentTimeMillis() - timenow;
HttpStatus statuscode = httpresult.getStatusCode();
if (statuscode != HttpStatus.OK) {
result = "yel";
adminlatency = 0;
}
httpClient.close();
// Error Caught
} catch (Exception e) {
result = "red";
adminlatency = 0;
}
return result;
}

World Pay Payment gateway Integration In ASP.Net MVC using C#

string xml = "<?xml version='1.0'? encoding='UTF-8'?><!DOCTYPE paymentService PUBLIC '-//WorldPay//DTD WorldPay PaymentService v1//EN''http://dtd.worldpay.com/paymentService_v1.dtd'><paymentService version='1.4' merchantCode='MYMERCHANTCODE'><submit><order orderCode='RecurringOrderCode'><description>Monthly subscription.</description><amount value='1399' currencyCode='EUR' exponent='2' /><orderContent>Your Original Order Content</orderContent> <paymentDetails><VISA-SSL> <cardNumber>4444333322221111</cardNumber><expiryDate> <date month='09' year='2019'/> </expiryDate> <cardHolderName>J. Shopper</cardHolderName><cvc>123</cvc> <cardAddress> <address> <street>47A Queensbridge Rd</street><postalCode>CB94BQ</postalCode><city>GB</city><countryCode>GB</countryCode><telephoneNumber>+44</telephoneNumber> </address> </cardAddress> </VISA-SSL> <session shopperIPAddress='100.100.100.100' id='0215ui8ib1' /> </paymentDetails></order></submit></paymentService>";
string url = "https://secure-test.worldpay.com/jsp/merchant/xml/paymentService.jsp";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//string s = "id="+Server.UrlEncode(xml);
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.ContentType = "text/xml;charset=utf-8";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr.ReadToEnd();
sr.Close();
res.Close();
return View();
I am using this code to integrate the Worldpay payment gateway API i am getting this error on getting response from line HttpWebResponse res = (HttpWebResponse)req.GetResponse();
the error is -401 Authorization Required
You need to add your credentials to the request, probably HTTP basic auth. Can do it like this:
req.Headers[HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(<username> + ":" + <password>));

Resources