How can I securely sign requests for Last.fm api?

I am trying to implement authorization through Last.fm. I am posting my arguments as a dictionary to simplify the signing. This is the code I use to sign my calls:

public static string SignCall(Dictionary<string, string> args) { IOrderedEnumerable<KeyValuePair<string, string>> sortedArgs = args.OrderBy(arg => arg.Key); string signature = sortedArgs.Select(pair => pair.Key + pair.Value). Aggregate((first, second) => first + second); return MD5(signature + SecretKey); } 

I checked the output in the debugger, it should be the same, however, I still get WebExceptions every time I try, that is, the API returns "Invalid Method Signature". This means that it does not accept the signature that SignCall creates.

Here is my code that I use to create the url if it helps:

 public static string GetSignedURI(Dictionary<string, string> args, bool get) { var stringBuilder = new StringBuilder(); if (get) stringBuilder.Append("http://ws.audioscrobbler.com/2.0/?"); foreach (var kvp in args) stringBuilder.AppendFormat("{0}={1}&", kvp.Key, kvp.Value); stringBuilder.Append("api_sig="+SignCall(args)); return stringBuilder.ToString(); } 

And a usage example to get a SessionKey:

 var args = new Dictionary<string, string> { {"method", "auth.getSession"}, {"api_key", ApiKey}, {"token", token} }; string url = GetSignedURI(args, true); 

EDIT:

Oh, and the code refers to the MD5 function, implemented as follows:

 public static string MD5(string toHash) { byte[] textBytes = Encoding.UTF8.GetBytes(toHash); var cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = cryptHandler.ComputeHash(textBytes); return hash.Aggregate("", (current, a) => current + a.ToString("x2")); } 

In addition, here is the API documentation: API - Last.fm , on this page with a detailed description of authorization.

+4
source share
1 answer

Your code works fine for me. What I've done:

0
source

Source: https://habr.com/ru/post/1309224/


All Articles