【问题标题】:How do I sign requests reliably for the Last.fm api?如何为 Last.fm api 可靠地签署请求?
【发布时间】:2010-05-09 02:38:07
【问题描述】:

我正在尝试通过 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();
}

以及获取 SessionKey 的示例用法:

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.fmthis page 详细授权。

【问题讨论】:

  • 具体的 Web Exception 是什么?
  • 它返回无效的方法签名,所以状态为 403。

标签: c# linq md5


【解决方案1】:

您的代码对我来说很好用。我做了什么:

  1. 获取令牌:http://ws.audioscrobbler.com/2.0/?method=auth.gettoken&api_key=677626cfada7f04fa80cfd3ad199b109,返回的令牌为53c8890afbbf94281931cd11bf28a4e0
  2. 使用用户验证该令牌:http://www.last.fm/api/auth?api_key=677626cfada7f04fa80cfd3ad199b109&token=53c8890afbbf94281931cd11bf28a4e0
  3. 使用您的代码获取 URL,然后使用返回用户名和会话密钥的 WebClient 下载其内容。

【讨论】:

  • 你是对的,它刚刚开始工作。不知道发生了什么。还是谢谢。
猜你喜欢
  • 2021-06-03
  • 2014-09-26
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
相关资源
最近更新 更多