我正在尝试通过 Last.fm 实现授权。我将我的论点作为字典提交,以使签名更容易。这是我用来签署我的电话的代码:
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);
}
我已经检查了调试器中的输出,它确实应该是这样,但是,我每次尝试时仍然会收到 WebExceptions,这意味着 API 正在返回“无效的方法签名”。这意味着它不接受 SignCall 正在生成的签名。
这是我用来生成 URL 的代码,以备不时之需:
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();
}
获取 session key 的示例用法:
var args = new Dictionary<string, string>
{
{"method", "auth.getSession"},
{"api_key", ApiKey},
{"token", token}
};
string url = GetSignedURI(args, true);
编辑:
哦,代码引用了这样实现的 MD5 函数:
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"));
}
此外,这是 API 文档:API - Last.fm , 与 this page详细授权。
最佳答案
您的代码对我来说工作正常。我做了什么:
- 获取 token :http://ws.audioscrobbler.com/2.0/?method=auth.gettoken&api_key=677626cfada7f04fa80cfd3ad199b109 ,返回的 token 是
53c8890afbbf94281931cd11bf28a4e0
- 向用户验证该 token :http://www.last.fm/api/auth?api_key=677626cfada7f04fa80cfd3ad199b109&token=53c8890afbbf94281931cd11bf28a4e0
- 使用您的代码获取 URL,然后使用返回用户名和 session key 的
WebClient
下载其内容。
关于c# - 如何为 Last.fm api 可靠地签署请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796422/