2014-05-11 5 views
4

Windows Azure blob 저장소 계정에 CORS 속성을 설정하려고합니다. ASP.NET 서버를 사용하여 PUT 요청을 보냅니다. 서버가 말하는 금지 응답, 다시 보내는Windows에서 CORS 설정 ASP.NET을 사용하여 Azure blob 저장소

"서버가 요청을 인증하는 데 실패했습니다. 인증 헤더의 값이 서명을 포함하여 제대로 형성되어 있는지 확인합니다.는"

는 그래서 뭔가해야 내 인증 헤더. 다음은 헤더를 가져 오는 데 사용하는 두 가지 함수입니다.

public string GetWindowsAzureAuthenticationHeader(string verb) 
{ 
    string stringToSign = String.Format("{0}\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:" + DateTime.UtcNow.ToString("R") + "\nx-ms-version:2013-08-15\n" // headers 
             + "/{1}\ncomp:properties\nrestype:service", verb, CloudConfig.StorageAccountName); 

    return SignThis(stringToSign, CloudConfig.StorageAccountKey, CloudConfig.StorageAccountName); 
} 

private string SignThis(string stringToSign, string key, string account) 
{ 
    string signature; 
    var unicodeKey = Convert.FromBase64String(key); 
    using (var hmacSha256 = new HMACSHA256(unicodeKey)) 
    { 
     var dataToHmac = Encoding.UTF8.GetBytes(stringToSign); 
     signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac)); 
    } 

    String authorizationHeader = String.Format(
     CultureInfo.InvariantCulture, 
     "{0} {1}:{2}", 
     "SharedKey", 
     account, 
     signature); 

    return authorizationHeader; 
} 

요청을 보내는 컨트롤러 작업입니다. _mediaFactory.GetWindowsAzureCors 메서드는 CORS 요청과 함께 XML 파일의 내용을 반환합니다.

var content = Encoding.UTF8.GetBytes(_mediaFactory.GetWindowsAzureCors(ControllerContext.HttpContext.Server)); 
var request = (HttpWebRequest)WebRequest.Create(CloudConfig.StorageAccountUri); 

request.Method = "PUT"; 
request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R")); 
request.Headers.Add("x-ms-version", "2013-08-15"); 
request.ContentType = "text/plain; charset=UTF-8"; 
request.Host = string.Format("{0}.blob.core.windows.net", CloudConfig.StorageAccountName); 
request.Headers.Add("Authorization", _mediaFactory.GetWindowsAzureAuthenticationHeader(request.Method)); 

request.GetRequestStream().Write(content, 0, content.Length); 
using (var response = (HttpWebResponse) request.GetResponse()) 
{ 
    model.StatusCode = response.StatusCode; 
    model.Response = response.StatusDescription; 
} 

내가 뭘 잘못하고 있니?

+0

주제 코멘트 끄기 : 여기에 그렇게 할 수있는 샘플 코드는 당신이 .NET 코드를 사용하는 경우, 당신은 CORS를 설정하고 직접 REST API를 소모하기위한 푸른 저장 클라이언트 라이브러리를 사용하지 않는 이유가있다. 그냥 궁금해서. –

+0

무식함. 어떻게해야합니까? –

답변

8

실제로는 매우 간단합니다.

먼저 프로젝트에 Azure Storage Client 라이브러리에 대한 참조를 추가하십시오. Nuget을 사용하는 경우 설치하려는 패키지는 WindowsAzure.Storage입니다.

그런 다음 CORS 설정을 지정하는 기능은 SetServiceProperties입니다.

  CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountKey), true); 
      var blobClient = storageAccount.CreateCloudBlobClient(); 
      ServiceProperties blobServiceProperties = new ServiceProperties(); 
      blobServiceProperties.Cors.CorsRules.Add(new CorsRule(){ 
       AllowedHeaders = new List<string>() {"*"}, 
       ExposedHeaders = new List<string>() {"*"}, 
       AllowedMethods = CorsHttpMethods.Post | CorsHttpMethods.Put | ... Other Allowed Methods, 
       AllowedOrigins = new List<string>() {"http://yourdomain.com", "https://yourdomain.com", "blah", "blah", "blah"}, 
       MaxAgeInSeconds = 3600, 
      }); 
      blobClient.SetServiceProperties(blobServiceProperties); 
+0

물론 나는 어려운 일들을 고집합니다. 그게 더 좋은 방법입니다. 감사합니다 Gaurav! –

관련 문제