快速代码与cosmosDB连接时出现授权错误

时间:2018-11-29 07:34:08

标签: swift azure-cosmosdb

我正在使用给定的masterKey生成令牌,但是它不起作用。这是我的代码。我正在使用cosmosDB文档中提到的base64解码密钥,然后将其转换为哈希码。

static func hmacSHA256(_ payload: String, withKey key: String) -> String? {
        var result: [CUnsignedChar]

let decodedData = key.data(using: .utf8)!
        let decodedString = decodedData.base64EncodedString(options: .lineLength76Characters)
        if let cKey = decodedString.cString(using: String.Encoding.utf8),
            let cData = payload.cString(using: String.Encoding.utf8) {
            let algo  = CCHmacAlgorithm(kCCHmacAlgSHA256)
            result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))

            CCHmac(algo, cKey, cKey.count-1, cData, cData.count-1, &result)
        } else {
            fatalError("Nil returned when processing input strings as UTF8")
        }

        let hashData = NSData(bytes: result, length: Int(CC_SHA256_DIGEST_LENGTH))
        let signiture = hashData.base64EncodedString(options: .lineLength76Characters)

        let authString = "type=master&ver=\(tokenVersion)&sig=\(signiture)"

        let authStringEncoded = authString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)!

        return authStringEncoded
    }

当我将此密钥传递到请求url时,它给出了未授权令牌的错误。

请帮助我解决Swift缺少的步骤。因为当我使用JavaScript代码时,它可以与CriptoJS一起使用。

谢谢

0 个答案:

没有答案