Generating Shared Access Signatures
Complete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
✦ Skip the page breaks and see fewer ads — read each lesson on a single page with Pro
Lesson: Generating and Managing Shared Access Signatures (SAS)
Introduction: Why Shared Access Signatures Matter
In the world of cloud storage, security is the foundation upon which all reliable architecture is built. When you store data in a cloud-based object storage system—such as Azure Blob Storage—you are often faced with a fundamental dilemma: how do you allow a user, an application, or a third-party service to access specific files without handing over your master account keys? If you provide your primary account keys, you grant full, unrestricted administrative access to every single byte of data in your storage account. This is a massive security risk, as a single compromised key could lead to a total data breach.
This is where Shared Access Signatures, or SAS, become essential. A Shared Access Signature is a URI (Uniform Resource Identifier) that grants restricted access rights to storage resources. By using a SAS, you can delegate access to your storage account without sharing your account keys. You define exactly what the user can do, which resources they can access, and for how long the access remains valid. In essence, SAS allows you to implement the principle of least privilege, ensuring that every entity interacting with your data has only the permissions it absolutely needs to perform its task.
Understanding how to generate and manage SAS tokens is a critical skill for any cloud engineer or developer. Whether you are building a web application that needs to upload user avatars directly to storage, or you are creating a temporary link for a client to download a specific report, SAS is the primary mechanism for secure, time-limited, and permission-scoped access control. This lesson will guide you through the mechanics of SAS, the different types available, and the best practices for implementing them safely in your production environments.
Understanding the Anatomy of a Shared Access Signature
At its core, a SAS is a signed string that contains a set of parameters. These parameters inform the storage service about the scope of the request, the permissions granted, the start and expiration times, and the cryptographic signature used to verify the request's authenticity. When a client makes a request to your storage account using a SAS, the storage service validates the signature against the account key or the user delegation key. If the signature is valid and the requested action falls within the parameters defined in the SAS string, the request is authorized.
The Key Components of a SAS URI
A SAS URI is appended to the base URL of your storage resource. It typically includes the following components:
- Version (sv): The version of the storage service protocol to use. This ensures that the storage service interprets the parameters correctly.
- Service (ss): The storage service being accessed, such as Blob, File, Queue, or Table.
- Resource Type (srt): The level of access, such as Service, Container, or Object.
- Permissions (sp): The specific operations allowed, such as Read (r), Write (w), Delete (d), or List (l).
- Start and Expiry (st, se): The window of time during which the SAS is valid.
- IP Address (sip): An optional parameter to restrict access to a specific IP address or range, adding a layer of network-level security.
- Protocol (spr): An optional parameter to restrict access to HTTPS only, which is highly recommended for security.
- Signature (sig): The cryptographic hash that proves the SAS was generated by an authorized entity.
Callout: SAS vs. Account Keys It is helpful to think of an Account Key as the master key to your entire house, while a SAS is a temporary key card issued to a guest. The master key grants access to every room, cabinet, and safe. The key card is programmed to open only the front door and perhaps one guest bedroom, and it automatically expires at the end of the guest's stay. Using SAS ensures that even if a guest's card is stolen, the damage is limited to the specific room they were granted access to, and the card will stop working regardless.
Types of Shared Access Signatures
There are three primary ways to implement Shared Access Signatures, and choosing the right one depends on your specific security requirements and infrastructure setup.
1. User Delegation SAS
A User Delegation SAS is secured with Microsoft Entra ID (formerly Azure Active Directory) credentials rather than your storage account keys. This is the most secure method because it does not require you to store your account keys in your application code or configuration. To create a User Delegation SAS, you first request a user delegation key using your Entra ID credentials, and then use that key to sign the SAS.
2. Service SAS
A Service SAS is signed with the storage account key. It delegates access to a resource in only one of the storage services: Blob, Queue, Table, or File. This is the most common form of SAS for simple applications where you need to provide temporary access to a specific container or blob.
3. Account SAS
An Account SAS is also signed with the storage account key, but it provides access to resources in one or more of the storage services. It can also grant access to operations that are not available with a Service SAS, such as getting storage service properties or service statistics. Because an Account SAS is so powerful, it should be used sparingly and only when necessary.
Step-by-Step: Generating a Service SAS
Generating a Service SAS can be done through the Azure Portal, the Azure CLI, or programmatically via the Azure SDKs. While the portal is great for quick, one-off tasks, programmatic generation is what you will use in production systems.
Using the Azure Portal
- Navigate to your storage account in the Azure Portal.
- Select the specific container or blob you wish to share.
- Right-click the resource and select "Generate SAS."
- Configure the permissions (e.g., Read, List).
- Set the start and expiry date/time.
- Choose the allowed protocol (HTTPS only).
- Click "Generate SAS token and URL."
Programmatic Generation (Python Example)
When building an application, you will likely generate SAS tokens on the fly. Here is a Python example using the azure-storage-blob library:
from datetime import datetime, timedelta
from azure.storage.blob import BlobServiceClient, BlobSasPermissions, generate_blob_sas
# Define connection string and resource details
connection_string = "your_connection_string_here"
container_name = "my-container"
blob_name = "report.pdf"
# Create the service client
service_client = BlobServiceClient.from_connection_string(connection_string)
# Generate a SAS token that expires in 1 hour
sas_token = generate_blob_sas(
account_name=service_client.account_name,
container_name=container_name,
blob_name=blob_name,
account_key=service_client.credential.account_key,
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)
# Construct the full URL
blob_url = f"{service_client.get_blob_client(container_name, blob_name).url}?{sas_token}"
print(f"Access URL: {blob_url}")
Note: Always ensure the expiry time is as short as possible. If a user only needs five minutes to download a file, do not grant them access for an hour or a day. Reducing the validity window significantly limits the impact of a leaked token.
Best Practices for Managing SAS
Managing SAS tokens requires a proactive approach to security. Because SAS tokens are essentially "bearer tokens"—meaning anyone who possesses the token can use it—they must be protected just as carefully as passwords.
1. Always Use HTTPS
Never allow a SAS to be used over HTTP. HTTPS encrypts the data in transit, preventing attackers from intercepting the token through man-in-the-middle attacks. When generating your SAS, explicitly restrict the allowed protocol to HTTPS.
2. Implement Stored Access Policies
A Stored Access Policy provides an additional layer of control on the server side. By creating a policy on your container, you can associate a SAS with that policy. If you ever need to revoke access, you can simply delete or modify the Stored Access Policy, and all SAS tokens associated with it will immediately stop working. This is a much better alternative to trying to track down and invalidate individual tokens.
3. Use User Delegation SAS Whenever Possible
As mentioned earlier, User Delegation SAS tokens rely on Entra ID credentials rather than the storage account key. If your storage account key is compromised, your entire account is at risk. By using User Delegation SAS, you ensure that even if the SAS generation process is compromised, the primary account keys remain safe.
4. Audit SAS Usage
Regularly monitor the logs for your storage account to see how SAS tokens are being used. Azure Storage provides diagnostic logs that can be sent to a Log Analytics workspace. Look for anomalous patterns, such as a large number of requests from an unexpected IP address or a high volume of requests for resources that are not typically accessed.
5. Rotate Account Keys Regularly
Even if you use SAS for most access, you must still rotate your primary and secondary storage account keys on a regular basis. Key rotation limits the lifetime of any credentials that might have been inadvertently exposed. When you rotate a key, ensure that your applications are updated to use the new key without downtime.
Common Pitfalls and How to Avoid Them
Even experienced developers can fall into traps when working with SAS. Below are some of the most common mistakes and strategies to avoid them.
Hardcoding SAS Tokens
Never hardcode a SAS token in your source code or configuration files. If you commit a hardcoded token to a version control system like GitHub, it is effectively public. Instead, generate tokens dynamically at runtime in a secure backend environment.
Over-Privileged Permissions
A common mistake is to grant more permissions than necessary. If a user only needs to download a file, do not grant "Write" or "Delete" permissions. If they only need to read one blob, do not grant access to the entire container. Always follow the principle of least privilege.
Excessive Expiration Times
Setting an expiration time of "one year" or "never" is a dangerous practice. If a token is leaked, it could provide an attacker with access to your data for an extended period. Always calculate the minimum time required for the operation and set the expiration accordingly.
Ignoring IP Restrictions
If you know that your users will always be connecting from a specific corporate network, use the IP address restriction feature to limit access to that specific range. This adds a powerful layer of defense, as even a stolen token will be useless if used from a different network.
Callout: The Power of Stored Access Policies Stored Access Policies are often overlooked, but they are a vital tool for incident response. If you identify that a set of SAS tokens has been compromised, you don't have to scramble to change your storage account keys—which would break all your applications. Instead, you simply update the Stored Access Policy, and the malicious access is cut off instantly. It is the closest thing you have to a "kill switch" for SAS.
Comparison of SAS Implementation Methods
To help you decide which approach is best for your specific use case, refer to the following comparison table:
| Feature | Service SAS | Account SAS | User Delegation SAS |
|---|---|---|---|
| Security Mechanism | Storage Account Key | Storage Account Key | Entra ID Credentials |
| Scope | Single Service/Resource | Multiple Services | Single Service/Resource |
| Revocation | Only via Stored Policy | Only via Key Rotation | Via Entra ID/Key Revocation |
| Best For | Common web app tasks | Admin/Management tasks | Highly secure, enterprise apps |
| Complexity | Low | Medium | High |
Troubleshooting SAS Issues
When a SAS request fails, the storage service will return an error code. Understanding these codes is essential for debugging.
- 403 Forbidden: This is the most common error. It usually means the SAS has expired, the signature is invalid, or the permissions granted do not include the operation being performed.
- 400 Bad Request: This often indicates that the SAS parameters are malformed or missing required components.
- 401 Unauthorized: This indicates an issue with the authentication process itself, often related to an invalid signature or an expired delegation key.
If you encounter a 403 error, start by checking the expiration time. Ensure that the server generating the token and the server receiving the request have synchronized clocks. If the clocks are out of sync, a perfectly valid token might be rejected because the service thinks it has already expired or is not yet valid.
Practical Application: Real-World Scenario
Imagine you are building a document management system for a law firm. Clients need to upload sensitive documents to a secure area of your storage account. You cannot give the client your account keys, and you cannot have them upload directly to your server (as it would be too slow and expensive).
The Solution:
- The client logs into your web application using their credentials.
- The application validates the client's request.
- The backend server generates a short-lived (e.g., 10-minute) SAS token that grants "Write" permission to a specific, unique folder for that client.
- The application provides the SAS URL to the client's browser.
- The client's browser uploads the file directly to the storage account using the SAS URL.
- Once the upload is complete, the SAS token expires, and the client no longer has access to the storage.
This architecture is secure, scalable, and keeps your backend servers from becoming a bottleneck for file transfers.
Key Takeaways
- SAS is for Delegation: Shared Access Signatures are the primary tool for granting limited, time-bound access to storage resources without revealing your master account keys.
- Principle of Least Privilege: Always grant the minimum permissions required for the shortest time possible. If a user only needs read access for five minutes, do not grant write access for an hour.
- Prioritize User Delegation SAS: Whenever possible, use User Delegation SAS, which relies on Entra ID credentials, to avoid exposing your primary storage account keys.
- Enforce HTTPS: Always restrict SAS access to HTTPS to protect the token and the data from interception during transit.
- Utilize Stored Access Policies: Use Stored Access Policies to provide a mechanism for immediate revocation of access if a security incident occurs.
- Never Hardcode Tokens: Keep your SAS generation logic in secure, server-side code. Never store tokens in configuration files or public repositories.
- Monitor and Audit: Regularly review storage logs to detect unusual access patterns or potential misuse of SAS tokens.
By following these principles, you can build a highly secure storage architecture that protects your data while providing the flexibility your applications need to function effectively. Remember that security is not a one-time task, but a continuous process of auditing, rotating, and refining your access control strategies.
Frequently Asked Questions
Can I revoke a SAS token after it has been issued?
If you used a Stored Access Policy to create the SAS, yes, you can revoke it by modifying or deleting the policy. If you created an ad-hoc SAS (one without a policy), it cannot be revoked; you must wait for it to expire or rotate your storage account keys.
Why does my SAS request return a 403 Forbidden error even though the token seems correct?
This is often due to a clock skew between the client and the server. Ensure that all your servers are synchronized using a service like NTP. Also, double-check that you are not trying to perform an operation (like "Delete") that wasn't included in the SAS permissions.
Is it safe to use SAS for public-facing assets?
Generally, no. If a file is meant to be public, you should set the container access level to "Blob" or "Container" rather than using SAS. SAS is designed for scenarios where you need to control who has access to the data.
How many SAS tokens can I create for a single resource?
There is no hard limit on the number of SAS tokens you can create. However, keep in mind that every request made with a SAS token counts toward your storage account's throughput and transaction limits.
Can I restrict a SAS token to a specific IP address?
Yes, you can use the sip parameter to specify an IP address or a range of IP addresses (CIDR notation). This is an excellent way to ensure that the token can only be used from a trusted network.
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles your daily points limit so you progress twice as fast, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× daily points limit
- ✓ Distraction-free lessons