Hi ,
Thanks for reaching out to Microsoft Q&A.
Your SAS token generation code appears close, but the authentication issue is likely due to incorrect permissions, missing signature, or an issue with how the SAS token is applied. Here are some steps to fix it:
- Fixing the SAS Token Generation:
- You need to explicitly call
.SetPermissions()
with read, write, and create permissions for upload operations. - Make sure the
ToSasQueryParameters()
method is correctly generating the SAS token.
Try this updated code:
BlobServiceClient client = new BlobServiceClient(AzureStorageConnectionString());
BlobContainerClient containerClient = client.GetBlobContainerClient("videos");
BlobClient blobClient = containerClient.GetBlobClient(sUserID + "/" + model.name);
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerClient.Name,
BlobName = blobClient.Name,
Resource = "b", // "b" for Blob-level SAS
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
};
// Correcting permissions - allowing write and create
sasBuilder.SetPermissions(BlobSasPermissions.Write | BlobSasPermissions.Create);
var sasToken = sasBuilder.ToSasQueryParameters(
new StorageSharedKeyCredential(AzureStorageAccountName(), AzureStorageSubscriptionKey()))
.ToString();
// Generate a full SAS URI
Uri sasURI = new Uri($"{blobClient.Uri}?{sasToken}");
// Use this full SAS URI for the client-side upload
string sSasToken = sasURI.ToString();
- Fixing client Side Code (TypeScript)
Ensure you're correctly using the SAS token to initialize the BlobServiceClient
:
// Use the correct SAS token URI, not just the token itself
this.blobServiceClient = new BlobServiceClient(sSasToken);
const containerClient = this.blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const opts: BlockBlobParallelUploadOptions = {
blockSize: 4 * 1024 * 1024, // 4MB blocks
onProgress: (progress: TransferProgressEvent) => {
this.handleProgress(progress.loadedBytes);
console.log("uploadData progress", progress);
},
abortSignal: this.abortSignal
};
// Uploading the file
const uploadBlobResponse: BlobUploadCommonResponse = await blockBlobClient.uploadData(this.file, opts);
console.log("uploadBlobResponse", uploadBlobResponse);
- Ensure your Storage Account Key is Correct
- Check if your SAS Token has a Signature (
sig=
in the URL) - Ensure the blob exists and container access allows SAS-based writes
- Permissions should include
Write
andCreate
- Use the full SAS URI in the client code (
https://storageaccount.blob.core.windows.net/container/blob?SAS
), not just the token
Please feel free to click the 'Upvote' (Thumbs-up) button and 'Accept as Answer'. This helps the community by allowing others with similar queries to easily find the solution.