Shared Access Signature
Tags: azure, security, signature, shared
Published: 2024-04-29 08:07:01


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 ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/win2n23227bd6x5zptxm.png)


![Azure Storage Setting to not allow public access while creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gqudhw85k506fjychexp.png)

**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**:
```typescript
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
    });
    }
}


```
**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 ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oxugsdj8ibfh8xipphfn.png)


**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
<table aria-label="How shared access signatures work" class="table">
<thead>
<tr>
<th width="30%">Component</th>
<th width="70%">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>sp=r</code></td>
<td>Controls the access rights. The values can be <code>a</code> for add, <code>c</code> for create, <code>d</code> for delete, <code>l</code> for list, <code>r</code> for read, or <code>w</code> for write. This example is read only. The example <code>sp=acdlrw</code> grants all the available rights.</td>
</tr>
<tr>
<td><code>st=2020-01-20T11:42:32Z</code></td>
<td>The date and time when access starts.</td>
</tr>
<tr>
<td><code>se=2020-01-20T19:42:32Z</code></td>
<td>The date and time when access ends. This example grants eight hours of access.</td>
</tr>
<tr>
<td><code>sv=2019-02-02</code></td>
<td>The version of the storage API to use.</td>
</tr>
<tr>
<td><code>sr=b</code></td>
<td>The kind of storage being accessed. In this example, b is for blob.</td>
</tr>
<tr>
<td><code>sig=SrW1HZ5Nb6MbRzTbXCaPm%2BJiSEn15tC91Y4umMPwVZs%3D</code></td>
<td>The cryptographic signature.</td>
</tr>
</tbody>
</table>



For more details, refer to [Implement shared access signatures
](https://learn.microsoft.com/en-us/training/modules/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.