azure REST API通信
我当前正在尝试从salesforce检索Azure帐户中可用的列表共享。我试图从以下示例代码中实现该示例:azure REST API通信,rest,azure,azure-hub,Rest,Azure,Azure Hub,我当前正在尝试从salesforce检索Azure帐户中可用的列表共享。我试图从以下示例代码中实现该示例: //私钥:我的帐户的访问密钥 字符串storageKey=私钥; 字符串storageName='accountName'; Datetime dt=Datetime.now(); 字符串formattedDate=dt.formattGMT('EEE,dd-MMM-yyy-HH:mm:ss')+'GMT'; 调试('formattedDate--'+formattedDate); 字符
//私钥:我的帐户的访问密钥
字符串storageKey=私钥;
字符串storageName='accountName';
Datetime dt=Datetime.now();
字符串formattedDate=dt.formattGMT('EEE,dd-MMM-yyy-HH:mm:ss')+'GMT';
调试('formattedDate--'+formattedDate);
字符串CanonicalizedHeaders='x-ms-date:'+formattedDate+'\nx ms版本:2016-05-31';
字符串CanonicalizedResource='/'+storageName+'/\ncomp:list';
字符串StringToSign='GET\n\n\n\n\n\n\n\n\n\n'+CanonicalizedHeaders+'\n'+CanonicalizedResource;
系统调试('StringToSign--'+StringToSign);
Blob temp=EncodingUtil.base64解码(storageKey);
Blob hmac=加密生成MAC('HmacSHA256',Blob.valueOf(StringToSign),温度)//StringToSign
system.debug('oo-'+EncodingUtil.base64Encode(hmac));
HttpRequest req=新的HttpRequest();
请求setMethod('GET');
//请求setHeader('content-type','application/xml');
要求设置标题('x-ms-version','2016-05-31');
请求setHeader('x-ms-date',formattedDate);
字符串签名=EncodingUtil.base64Encode(hmac);
字符串authHeader='SharedKey salesforcestrongaccount'+':'+签名;
请求setHeader(“授权”,authHeader);
请求setEndpoint('https://.file.core.windows.net/?comp=list');
Http=newhttp();
HTTPResponse;
res=http.send(req);
调试(LoggingLevel.INFO,'http.send result status:'+res.getStatus());
有什么帮助吗?正如Gaurav Mantri所说,您的stringToSign有问题。所以你会得到这个错误 正确的共享密钥身份验证如下所示:
StringToSign = VERB + "\n" +
Content-Encoding + "\n" +
Content-Language + "\n" +
Content-Length + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
If-Modified-Since + "\n" +
If-Match + "\n" +
If-None-Match + "\n" +
If-Unmodified-Since + "\n" +
Range + "\n" +
CanonicalizedHeaders +
CanonicalizedResource;
这里我创建了一个测试演示,您可以参考它
列表共享:
string storageAccount = "storage account";
string accessKey = "accountkey";
string resourcePath = "?comp=list";
string uri = @"https://" + storageAccount + ".file.core.windows.net/" + resourcePath;
// Web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
request.Headers["x-ms-version"] = "2015-02-21";
String stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + request.Headers["x-ms-date"] + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + storageAccount + "/" + "\ncomp:list"; // resources
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
string strAuthorization = "SharedKey " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));
request.Headers["Authorization"] = strAuthorization;
Task<WebResponse> response = request.GetResponseAsync();
HttpWebResponse responseresult = (HttpWebResponse)response.Result;
using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
{
string jsonData = r.ReadToEnd();
Console.WriteLine(jsonData);
}
计算
stringToSign
的方式存在问题。请按照此处概述的说明进行操作:然后重试您的请求。您是否可以为此提供任何示例代码。因为我尝试了链接中指定的过程。巴顿·勒克诺:你没有按照那里的指示去做。我快速浏览了一下你的代码,就明白了。我建议您再仔细阅读一下文档。否则,如果您搜索Azure Storage REST API示例,我相信您会找到足够的源代码。我使用SHA256创建了一个MAC密钥,您可以在上面的代码中看到。我有什么遗漏吗?请检查创建stringToSign的文档。这就是你代码中的问题所在。我能知道你是在哪个平台上执行的吗?它是用java写的吗#BrandoI尝试了上述stringtosign格式,但在使用键@Brando ThangThank You#Brando Zhag时出现了相同的错误。Java代码执行得非常完美。但是,当我将逻辑转换为salesforce时,我仍然面临403错误。有什么想法吗?还有一个观察是,我可以通过邮递员应用程序调用azure api。但是,当我在sf中使用相同的键n date时,它抛出403错误。我猜salesforce可能会在您的请求中添加一些自定义头。我建议您可以使用fiddler获取请求,以检查其中是否有任何其他请求头。
string storageAccount = "storage account";
string accessKey = "accountkey";
string resourcePath = "?comp=list";
string uri = @"https://" + storageAccount + ".file.core.windows.net/" + resourcePath;
// Web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
request.Headers["x-ms-version"] = "2015-02-21";
String stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + request.Headers["x-ms-date"] + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + storageAccount + "/" + "\ncomp:list"; // resources
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
string strAuthorization = "SharedKey " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));
request.Headers["Authorization"] = strAuthorization;
Task<WebResponse> response = request.GetResponseAsync();
HttpWebResponse responseresult = (HttpWebResponse)response.Result;
using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
{
string jsonData = r.ReadToEnd();
Console.WriteLine(jsonData);
}
private static final String account = "accountname";
private static final String key = "Key";
public static void main(String args[]) throws Exception {
// String urlString = "http://" + account + ".file.core.windows.net/sampleshare/name.txt";
String urlString = "https://" + account + ".file.core.windows.net/?comp=list";
HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
getFileRequest(connection, account, key);
connection.connect();
System.out.println("Response message : " + connection.getResponseMessage());
System.out.println("Response code : " + connection.getResponseCode());
BufferedReader br = null;
if (connection.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
public static void getFileRequest(HttpURLConnection request, String account, String key) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
String stringToSign = "GET\n" + "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + date + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + account + request.getURL().getPath() + "\ncomp:list"; // resources
System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
request.setRequestMethod("GET");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2015-02-21");
request.setRequestProperty("Authorization", auth);
}
private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
String auth = "SharedKey " + account + ":" + authKey;
return auth;
}