DEV Community

Cover image for Shared Access Signature
YogitaKadam14
YogitaKadam14

Posted on

Shared Access Signature

A shared access signature (SAS) is a URI that grants restricted access rights to Azure Storage resources. You can provide a shared access signature to clients that you want to grant delegate access to certain storage account resources.

Types of shared access signatures:

  1. User delegation SAS: A user delegation SAS applies to Blob storage only.
  2. Service SAS: A service SAS delegates access to a resource in many of the Azure Storage services.
  3. Account SAS: An account SAS delegates access to resources in one or more of the storage services.

When to implement shared access signatures

  • A common scenario where SAS is useful is a service where users read and write their data to their storage account.
  • When you copy a blob to another blob that resides in a different storage account, you must use an SAS to authorize access to the source blob. You can optionally use a SAS to authorize access to the destination blob as well.

How shared access signatures work?

SAS provides temporary, limited access to Azure Storage resources by granting specific permissions and duration through a generated token, ensuring secure and controlled sharing without exposing sensitive credentials.

Use Case: Secure Data Sharing

Scenario:
A company needs to securely share confidential documents stored in Azure Blob Storage with external partners for a limited time.

The settings below are configured on Azure Storage to restrict access for anonymous users from accessing the storage directly from the public network without a SAS (Shared Access Signature).

Azure Storage Setting to not allow public access

Azure Storage Setting to not allow public access while creation

Note: The most flexible and secure way to use a service or account SAS is to associate the SAS tokens with a stored access policy.

Node js sample code to generate SAS URI:

import { Request, Response } from "express";
import {BlobServiceClient} from '@azure/storage-blob';
import azureStorage from "azure-storage";
require('dotenv').config()
async function  generateSASURL(req:Request,res:Response) {
    try
    {         
    //read the file name received from the client 
    const blobName:string = req.body.blobName; 
    const containerName:string =req.body.containerName;
    const sasUrlExpiryInMinutes:number= req.body.sasUrlExpiryInMinutes;  
      //Best practice: create time limits
      //const MINUTES:number = sasUrlExpiryInMinutes;
      const NOW = new Date();  
      // Best practice: set the start time a little before the current time to 
      // make sure any clock issues are avoided    
      const MINUTES_BEFORE_NOW = new Date(NOW.valueOf() - sasUrlExpiryInMinutes * 60 * 1000); 
      const MINUTES_AFTER_NOW = new Date(NOW.valueOf() + sasUrlExpiryInMinutes * 60 * 1000); 

      var sharedAccessPolicy = {
        AccessPolicy: {
            Permissions: "r",
            Start: MINUTES_BEFORE_NOW,
            Expiry: MINUTES_AFTER_NOWv
        }
    };

    const conStr:string = process.env.AZURE_STORAGE_CONNECTION_STRING || '';
    const blobService =  azureStorage.createBlobService(
      conStr
    );

    var sasToken = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
    var sasUrl=blobService.getUrl(containerName,blobName,sasToken); //shared access signature URL
    var url=blobService.getUrl(containerName,blobName) //Normal URL   
    return res.status(200).json({
        "sasUrl":sasUrl,
        "url":url
    });
    }
    catch{
      console.error(new Error('Error generating SAS URL, method- GenerateSASURL').stack)
      res.status(500).json({
        "error":new Error('Error generating SAS URL, method- GenerateSASURL').stack
    });
    }
}


Enter fullscreen mode Exit fullscreen mode

SAS Configuration:
Define a shared access policy object specifying the permissions (Permissions), start time (Start), and expiry time (Expiry) for the SAS token.
Azure Blob Service Setup:
Retrieve the Azure Storage connection string from environment variables.
Create an Azure Blob Service client using the connection string.

Azure Storage Connection String

Generate SAS Token:
Generate a shared access signature (SAS) token for the specified container and blob using the shared access policy.
Generate URLs:
Generate URLs for accessing the blob: one with the SAS token appended (sasUrl) and one without (url).

SAS URL comprises two components: The first part is the URI to the resource you wish to access. The second part is a SAS token, which you've generated to authorize access to that resource.

You can split the URI from the SAS token within a single URI like this:
URI: https://medicalrecords.blob.core.windows.net/patient-images/patient-116139-nq8z7f.jpg?
SAS token: sp=r&st=2020-01-20T11:42:32Z&se=2020-01-20T19:42:32Z&spr=https&sv=2019-02-02&sr=b&sig=SrW1HZ5Nb6MbRzTbXCaPm%2BJiSEn15tC91Y4umMPwVZs%3D

Component Description
sp=r Controls the access rights. The values can be a for add, c for create, d for delete, l for list, r for read, or w for write. This example is read only. The example sp=acdlrw grants all the available rights.
st=2020-01-20T11:42:32Z The date and time when access starts.
se=2020-01-20T19:42:32Z The date and time when access ends. This example grants eight hours of access.
sv=2019-02-02 The version of the storage API to use.
sr=b The kind of storage being accessed. In this example, b is for blob.
sig=SrW1HZ5Nb6MbRzTbXCaPm%2BJiSEn15tC91Y4umMPwVZs%3D The cryptographic signature.

For more details, refer to Implement shared access signatures
.

Top 10 Best Practices for Shared Access Signatures (SAS) in Azure Storage

  1. Least Privilege: Grant only necessary permissions.
  2. Short Expiry: Set short token expiry times.
  3. Renewal and Rotation: Regularly renew and rotate tokens.
  4. Restricted Scope: Limit tokens to specific resources.
  5. Secure Transmission: Transmit tokens securely over HTTPS.
  6. Monitoring and Logging: Monitor token usage and log activities.
  7. Revocation Mechanism: Have a way to revoke tokens.
  8. Stored Access Policies: Use stored policies for centralized management.
  9. Token Scope Awareness: Educate users about token scope.
  10. Regular Security Audits: Conduct periodic security audits

In conclusion, shared access signatures (SAS) in Azure Storage offers controlled access to resources, empowering users to manage permissions effectively. Understanding the different types of SAS and leveraging associated access policies ensures secure data sharing. The provided Node.js sample demonstrates SAS URL generation for secure blob access, enhancing data protection in Azure Storage.

Top comments (0)