Azure blob authorization header

2019-09-18 16:39发布

问题:

I am trying to use refit to upload to azure blob storage from a Xamarin iOS application. This is the interface configuration I am using for Refit:

[Headers("x-ms-blob-type: BlockBlob")]
[Put("/{fileName}")]
Task<bool> UploadAsync([Body]byte[] content, string sasTokenKey,
[Header("Content-Type")] string contentType);

Where the sasTokenKey parameter looks like this:

"/content-default/1635839001660743375-66f93195-e923-4c8b-a3f1-5f3f9ba9dd32.jpeg?sv=2015-04-05&sr=b&sig=Up26vDxQikFqo%2FDQjRB08YtmK418rZfKx1IHbYKAjIE%3D&se=2015-11-23T18:59:26Z&sp=w"

This is how I am using Refit to call the azure blob server:

var myRefitApi = RestService.For<IMyRefitAPI>("https://myaccount.blob.core.windows.net");
myRefitApi.UploadAsync(photoBytes, sasTokenKey, "image/jpeg"

However I am getting the follow error:

Response status code does not indicate success: 403 (Server failed to 
authenticate the request. Make sure the value of Authorization header is 
formed correctly including the signature.)

The SAS url is working fine if I call it directly like this

var content = new StreamContent(stream);
            content.Headers.Add("Content-Type", "jpeg");
            content.Headers.Add("x-ms-blob-type", "BlockBlob");
var task = HttpClient.PutAsync(new Uri(sasTokenUrl), content);
task.Wait();

So basically I am just trying to do the same thing using Refit. Any idea how to get Refit working with Azure Blob Storage?

Thanks!

[UPDATE] I am now able to upload the bytes to the azure blob server but something seems to be wrong with the byte data because I am not able to view the image. Here is the code I am using to convert to byte array.

byte[] bytes;
using (var ms = new MemoryStream())
{
   stream.Position = 0;
   stream.CopyTo(ms);
   ms.Position = 0;
   bytes = ms.ToArray();
}

[UPDATE] Got it fixed by using stream instead of byte array!

回答1:

I see %2F and %3D and I'm curious if refit is encoding those a second time. Try sending the token without encoding it.



回答2:

This is incorrect use of Authorization header. You use Authorization header when you want to authorize the requests using account key. If you have the Shared Access Signature then you really don't need this header as the authorization information is included in the SAS itself. You can simply use the SAS URL for uploading files.