【问题标题】:HTTP MAC Authentication using C#使用 C# 的 HTTP MAC 身份验证
【发布时间】:2012-09-24 14:50:55
【问题描述】:

我正在尝试为正在开发的新 tent.io 协议创建一个客户端,他们正在使用https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-http-mac-01 描述的 HTTP MAC Oauth2 方案。

我在 C# 中编写了一个创建授权标头的简单方法,但是当我提交请求时,我收到一个简单的“无效 MAC 签名”错误。

由于我没有参考实现,我很难弄清楚我的代码有什么问题。我把它贴在这里希望有人能发现我的错误。

public string GetAuthorizationHeader(string macKeyIdentifier, string macKey, string macAlgorithm, string method, Uri uri)
{
    TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
    string timestamp = ((int)t.TotalSeconds).ToString();

    string nonce = new Random().Next().ToString();

    string normalizedString = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n\n", 
                                            timestamp, 
                                            nonce, 
                                            method,
                                            uri.PathAndQuery, 
                                            uri.Host, 
                                            uri.Port);

    HashAlgorithm hashGenerator = null;
    if (macAlgorithm == "hmac-sha-256")
    {
        hashGenerator = new HMACSHA256(Encoding.ASCII.GetBytes(macKey));
    }
    else if (macAlgorithm == "hmac-sha-1")
    {
        hashGenerator = new HMACSHA1(Encoding.ASCII.GetBytes(macKey));
    }
    else
    {
        throw new InvalidOperationException("Unsupported MAC algorithm");
    }

    string hash = System.Convert.ToBase64String(hashGenerator.ComputeHash(Encoding.ASCII.GetBytes(normalizedString)));

    StringBuilder authorizationHeader = new StringBuilder();
    authorizationHeader.AppendFormat(@"id=""{0}"",ts=""{1}"",nonce=""{2}"",mac=""{3}""",
                                     macKeyIdentifier, timestamp, nonce, hash);

    return authorizationHeader.ToString();
}

我使用返回的值创建了完整的标头,它看起来像这样

授权:MAC id="a:dfsdfa2",ts="1349277638",nonce="1469030797",mac="ibZ/HXaoz2VgBer3CK7K9vu0po3K+E36K+TQ9Sgcw6o="

我确定我遗漏了一些小东西,但我看不到它。

任何帮助将不胜感激!

【问题讨论】:

  • 你需要重新格式化你的代码

标签: c# .net oauth-2.0 hmac


【解决方案1】:

http://buchananweb.co.uk/security01.aspx 上执行良好的工具显示了使用 MD5 和 SHA1、SHA256、SHA384、SHA512 的 HMAC

【讨论】:

  • 我的代码生成的哈希值。不幸的是,我传递了错误的方法名称,所以签名无效。
【解决方案2】:

事实证明上面的代码是完美的,但是我传递了错误的 HTTP 方法值!

我收到错误的地方是 POST'ing JSON,但实际上我已将“GET”放入 GetAuthorizationMethod!

一旦我纠正了这个问题,我就从 Tent.is 获得了一个 access_token 值。

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多