Documentation ¶
Overview ¶
Example (ServiceSAS) ¶
package main import ( "context" "fmt" "io" "log" "os" "strings" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" ) func handleError(err error) { if err != nil { log.Fatal(err.Error()) } } func main() { accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY") const containerName = "testContainer" credential, err := azblob.NewSharedKeyCredential(accountName, accountKey) handleError(err) sasQueryParams, err := sas.BlobSignatureValues{ Protocol: sas.ProtocolHTTPS, StartTime: time.Now().UTC(), ExpiryTime: time.Now().UTC().Add(48 * time.Hour), Permissions: to.Ptr(sas.BlobPermissions{Read: true, Create: true, Write: true, Tag: true}).String(), ContainerName: containerName, }.SignWithSharedKey(credential) handleError(err) sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sasQueryParams.Encode()) fmt.Println(sasURL) // This URL can be used to authenticate requests now azClient, err := azblob.NewClientWithNoCredential(sasURL, nil) handleError(err) const blobData, blobName = "test data", "testBlob" uploadResp, err := azClient.UploadStream(context.TODO(), containerName, blobName, strings.NewReader(blobData), &azblob.UploadStreamOptions{ Metadata: map[string]*string{"Foo": to.Ptr("Bar")}, Tags: map[string]string{"Year": "2022"}, }) handleError(err) fmt.Println(uploadResp) blobDownloadResponse, err := azClient.DownloadStream(context.TODO(), containerName, blobName, nil) handleError(err) reader := blobDownloadResponse.Body downloadData, err := io.ReadAll(reader) handleError(err) fmt.Println(string(downloadData)) if string(downloadData) != blobData { log.Fatal("Uploaded data should be same as downloaded data") } err = reader.Close() if err != nil { return } }
Output:
Example (UserDelegationSAS) ¶
package main import ( "context" "fmt" "log" "os" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service" ) func handleError(err error) { if err != nil { log.Fatal(err.Error()) } } func main() { accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME") if !ok { panic("AZURE_STORAGE_ACCOUNT_NAME could not be found") } tenantID, ok := os.LookupEnv("AZURE_TENANT_ID") if !ok { panic("AZURE_TENANT_ID could not be found") } clientID, ok := os.LookupEnv("AZURE_CLIENT_ID") if !ok { panic("AZURE_CLIENT_ID could not be found") } clientSecret, ok := os.LookupEnv("AZURE_CLIENT_SECRET") if !ok { panic("AZURE_CLIENT_SECRET could not be found") } const containerName = "testcontainer" cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, clientSecret, nil) handleError(err) svcClient, err := service.NewClient( fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), cred, &service.ClientOptions{}, ) handleError(err) // Set current and past time and create key now := time.Now().UTC().Add(-10 * time.Second) expiry := now.Add(48 * time.Hour) info := service.KeyInfo{ Start: to.Ptr(now.UTC().Format(sas.TimeFormat)), Expiry: to.Ptr(expiry.UTC().Format(sas.TimeFormat)), } udc, err := svcClient.GetUserDelegationCredential(context.Background(), info, nil) handleError(err) // Create Blob Signature Values with desired permissions and sign with user delegation credential sasQueryParams, err := sas.BlobSignatureValues{ Protocol: sas.ProtocolHTTPS, StartTime: time.Now().UTC().Add(time.Second * -10), ExpiryTime: time.Now().UTC().Add(15 * time.Minute), Permissions: to.Ptr(sas.ContainerPermissions{Read: true, List: true}).String(), ContainerName: containerName, }.SignWithUserDelegation(udc) handleError(err) sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sasQueryParams.Encode()) // This URL can be used to authenticate requests now azClient, err := azblob.NewClientWithNoCredential(sasURL, nil) handleError(err) // list blobs in container pager := azClient.NewListBlobsFlatPager(containerName, nil) for pager.More() { resp, err := pager.NextPage(context.Background()) handleError(err) for _, b := range resp.Segment.BlobItems { fmt.Println(*b.Name) } } // User Delegation SAS doesn't support operations like creation, deletion or listing of containers // For more details, see https://docs.microsoft.com/rest/api/storageservices/create-user-delegation-sas#specify-permissions _, err = azClient.CreateContainer(context.Background(), "newcontainer", nil) if err != nil { fmt.Println("Containers can't be created using User Delegation SAS") } _, err = azClient.DeleteContainer(context.Background(), containerName, nil) if err != nil { fmt.Println("Containers can't be deleted using User Delegation SAS") } }
Output:
Index ¶
- Constants
- Variables
- type AccountPermissions
- type AccountResourceTypes
- type AccountSignatureValues
- type BlobPermissions
- type BlobSignatureValues
- type ContainerPermissions
- type IPEndpointStyleInfo
- type IPRange
- type Protocol
- type QueryParameters
- func (p *QueryParameters) AuthorizedObjectID() string
- func (p *QueryParameters) CacheControl() string
- func (p *QueryParameters) ContentDisposition() string
- func (p *QueryParameters) ContentEncoding() string
- func (p *QueryParameters) ContentLanguage() string
- func (p *QueryParameters) ContentType() string
- func (p *QueryParameters) Encode() string
- func (p *QueryParameters) EncryptionScope() string
- func (p *QueryParameters) ExpiryTime() time.Time
- func (p *QueryParameters) IPRange() IPRange
- func (p *QueryParameters) Identifier() string
- func (p *QueryParameters) Permissions() string
- func (p *QueryParameters) Protocol() Protocol
- func (p *QueryParameters) Resource() string
- func (p *QueryParameters) ResourceTypes() string
- func (p *QueryParameters) Services() string
- func (p *QueryParameters) Signature() string
- func (p *QueryParameters) SignedCorrelationID() string
- func (p *QueryParameters) SignedDirectoryDepth() string
- func (p *QueryParameters) SignedExpiry() time.Time
- func (p *QueryParameters) SignedOID() string
- func (p *QueryParameters) SignedService() string
- func (p *QueryParameters) SignedStart() time.Time
- func (p *QueryParameters) SignedTID() string
- func (p *QueryParameters) SignedVersion() string
- func (p *QueryParameters) SnapshotTime() time.Time
- func (p *QueryParameters) StartTime() time.Time
- func (p *QueryParameters) UnauthorizedObjectID() string
- func (p *QueryParameters) Version() string
- type SharedKeyCredential
- type URLParts
- type UserDelegationCredential
Examples ¶
Constants ¶
const (
TimeFormat = "2006-01-02T15:04:05Z" // "2017-07-27T00:00:00Z" // ISO 8601
)
TimeFormat represents the format of a SAS start or expiry time. Use it when formatting/parsing a time.Time.
Variables ¶
var ( // Version is the default version encoded in the SAS token. Version = generated.ServiceVersion )
Functions ¶
This section is empty.
Types ¶
type AccountPermissions ¶
type AccountPermissions struct {
Read, Write, Delete, DeletePreviousVersion, PermanentDelete, List, Add, Create, Update, Process, FilterByTags, Tag, SetImmutabilityPolicy bool
}
AccountPermissions type simplifies creating the permissions string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSignatureValues' Permissions field.
func (*AccountPermissions) String ¶
func (p *AccountPermissions) String() string
String produces the SAS permissions string for an Azure Storage account. Call this method to set AccountSignatureValues' Permissions field.
type AccountResourceTypes ¶
type AccountResourceTypes struct {
Service, Container, Object bool
}
AccountResourceTypes type simplifies creating the resource types string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSignatureValues' ResourceTypes field.
func (*AccountResourceTypes) String ¶
func (rt *AccountResourceTypes) String() string
String produces the SAS resource types string for an Azure Storage account. Call this method to set AccountSignatureValues' ResourceTypes field.
type AccountSignatureValues ¶
type AccountSignatureValues struct { Version string `param:"sv"` // If not specified, this format to SASVersion Protocol Protocol `param:"spr"` // See the SASProtocol* constants StartTime time.Time `param:"st"` // Not specified if IsZero ExpiryTime time.Time `param:"se"` // Not specified if IsZero Permissions string `param:"sp"` // Create by initializing AccountPermissions and then call String() IPRange IPRange `param:"sip"` ResourceTypes string `param:"srt"` // Create by initializing AccountResourceTypes and then call String() EncryptionScope string `param:"ses"` }
AccountSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage account. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-an-account-sas
func (AccountSignatureValues) SignWithSharedKey ¶
func (v AccountSignatureValues) SignWithSharedKey(sharedKeyCredential *SharedKeyCredential) (QueryParameters, error)
SignWithSharedKey uses an account's shared key credential to sign this signature values to produce the proper SAS query parameters.
type BlobPermissions ¶
type BlobPermissions struct {
Read, Add, Create, Write, Delete, DeletePreviousVersion, PermanentDelete, List, Tag, Move, Execute, Ownership, Permissions, SetImmutabilityPolicy bool
}
BlobPermissions type simplifies creating the permissions string for an Azure Storage blob SAS. Initialize an instance of this type and then call its String method to set BlobSignatureValues' Permissions field.
func (*BlobPermissions) String ¶
func (p *BlobPermissions) String() string
String produces the SAS permissions string for an Azure Storage blob. Call this method to set BlobSignatureValues' Permissions field.
type BlobSignatureValues ¶
type BlobSignatureValues struct { Version string `param:"sv"` // If not specified, this defaults to Version Protocol Protocol `param:"spr"` // See the Protocol* constants StartTime time.Time `param:"st"` // Not specified if IsZero ExpiryTime time.Time `param:"se"` // Not specified if IsZero SnapshotTime time.Time Permissions string `param:"sp"` // Create by initializing ContainerPermissions or BlobPermissions and then call String() IPRange IPRange `param:"sip"` Identifier string `param:"si"` ContainerName string BlobName string // Use "" to create a Container SAS Directory string // Not nil for a directory SAS (ie sr=d) CacheControl string // rscc ContentDisposition string // rscd ContentEncoding string // rsce ContentLanguage string // rscl ContentType string // rsct BlobVersion string // sr=bv AuthorizedObjectID string // saoid CorrelationID string // scid EncryptionScope string `param:"ses"` }
BlobSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage container or blob. For more information on creating service sas, see https://docs.microsoft.com/rest/api/storageservices/constructing-a-service-sas For more information on creating user delegation sas, see https://docs.microsoft.com/rest/api/storageservices/create-user-delegation-sas
func (BlobSignatureValues) SignWithSharedKey ¶
func (v BlobSignatureValues) SignWithSharedKey(sharedKeyCredential *SharedKeyCredential) (QueryParameters, error)
SignWithSharedKey uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS query parameters.
func (BlobSignatureValues) SignWithUserDelegation ¶
func (v BlobSignatureValues) SignWithUserDelegation(userDelegationCredential *UserDelegationCredential) (QueryParameters, error)
SignWithUserDelegation uses an account's UserDelegationCredential to sign this signature values to produce the proper SAS query parameters.
type ContainerPermissions ¶
type ContainerPermissions struct {
Read, Add, Create, Write, Delete, DeletePreviousVersion, List, Tag, FilterByTags, Move, SetImmutabilityPolicy bool
Execute, ModifyOwnership, ModifyPermissions bool // Meant for hierarchical namespace accounts
}
ContainerPermissions type simplifies creating the permissions string for an Azure Storage container SAS. Initialize an instance of this type and then call its String method to set BlobSignatureValues' Permissions field. All permissions descriptions can be found here: https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#permissions-for-a-directory-container-or-blob
func (*ContainerPermissions) String ¶
func (p *ContainerPermissions) String() string
String produces the SAS permissions string for an Azure Storage container. Call this method to set BlobSignatureValues' Permissions field.
type IPEndpointStyleInfo ¶
type IPEndpointStyleInfo struct {
AccountName string // "" if not using IP endpoint style
}
IPEndpointStyleInfo is used for IP endpoint style URL when working with Azure storage emulator. Ex: "https://10.132.141.33/accountname/containername"
type IPRange ¶
type IPRange struct { Start net.IP // Not specified if length = 0 End net.IP // Not specified if length = 0 }
IPRange represents a SAS IP range's start IP and (optionally) end IP.
type QueryParameters ¶
type QueryParameters struct {
// contains filtered or unexported fields
}
QueryParameters object represents the components that make up an Azure Storage SAS' query parameters. You parse a map of query parameters into its fields by calling NewQueryParameters(). You add the components to a query parameter map by calling AddToValues(). NOTE: Changing any field requires computing a new SAS signature using a XxxSASSignatureValues type. This type defines the components used by all Azure Storage resources (Containers, Blobs, Files, & Queues).
func NewQueryParameters ¶
func NewQueryParameters(values url.Values, deleteSASParametersFromValues bool) QueryParameters
NewQueryParameters creates and initializes a QueryParameters object based on the query parameter map's passed-in values. If deleteSASParametersFromValues is true, all SAS-related query parameters are removed from the passed-in map. If deleteSASParametersFromValues is false, the map passed-in map is unaltered.
func (*QueryParameters) AuthorizedObjectID ¶ added in v0.6.0
func (p *QueryParameters) AuthorizedObjectID() string
AuthorizedObjectID returns authorizedObjectID.
func (*QueryParameters) CacheControl ¶
func (p *QueryParameters) CacheControl() string
CacheControl returns cacheControl.
func (*QueryParameters) ContentDisposition ¶
func (p *QueryParameters) ContentDisposition() string
ContentDisposition returns contentDisposition.
func (*QueryParameters) ContentEncoding ¶
func (p *QueryParameters) ContentEncoding() string
ContentEncoding returns contentEncoding.
func (*QueryParameters) ContentLanguage ¶
func (p *QueryParameters) ContentLanguage() string
ContentLanguage returns contentLanguage.
func (*QueryParameters) ContentType ¶
func (p *QueryParameters) ContentType() string
ContentType returns contentType.
func (*QueryParameters) Encode ¶
func (p *QueryParameters) Encode() string
Encode encodes the SAS query parameters into URL encoded form sorted by key.
func (*QueryParameters) EncryptionScope ¶ added in v1.2.0
func (p *QueryParameters) EncryptionScope() string
EncryptionScope returns encryptionScope
func (*QueryParameters) ExpiryTime ¶
func (p *QueryParameters) ExpiryTime() time.Time
ExpiryTime returns expiryTime.
func (*QueryParameters) IPRange ¶
func (p *QueryParameters) IPRange() IPRange
IPRange returns ipRange.
func (*QueryParameters) Identifier ¶
func (p *QueryParameters) Identifier() string
Identifier returns identifier.
func (*QueryParameters) Permissions ¶
func (p *QueryParameters) Permissions() string
Permissions returns permissions.
func (*QueryParameters) Protocol ¶
func (p *QueryParameters) Protocol() Protocol
Protocol returns protocol.
func (*QueryParameters) Resource ¶
func (p *QueryParameters) Resource() string
Resource returns resource.
func (*QueryParameters) ResourceTypes ¶
func (p *QueryParameters) ResourceTypes() string
ResourceTypes returns resourceTypes.
func (*QueryParameters) Services ¶
func (p *QueryParameters) Services() string
Services returns services.
func (*QueryParameters) Signature ¶
func (p *QueryParameters) Signature() string
Signature returns signature.
func (*QueryParameters) SignedCorrelationID ¶
func (p *QueryParameters) SignedCorrelationID() string
SignedCorrelationID returns signedCorrelationID.
func (*QueryParameters) SignedDirectoryDepth ¶
func (p *QueryParameters) SignedDirectoryDepth() string
SignedDirectoryDepth returns signedDirectoryDepth.
func (*QueryParameters) SignedExpiry ¶
func (p *QueryParameters) SignedExpiry() time.Time
SignedExpiry returns signedExpiry.
func (*QueryParameters) SignedOID ¶
func (p *QueryParameters) SignedOID() string
SignedOID returns signedOID.
func (*QueryParameters) SignedService ¶
func (p *QueryParameters) SignedService() string
SignedService returns signedService.
func (*QueryParameters) SignedStart ¶
func (p *QueryParameters) SignedStart() time.Time
SignedStart returns signedStart.
func (*QueryParameters) SignedTID ¶
func (p *QueryParameters) SignedTID() string
SignedTID returns signedTID.
func (*QueryParameters) SignedVersion ¶
func (p *QueryParameters) SignedVersion() string
SignedVersion returns signedVersion.
func (*QueryParameters) SnapshotTime ¶
func (p *QueryParameters) SnapshotTime() time.Time
SnapshotTime returns snapshotTime.
func (*QueryParameters) StartTime ¶
func (p *QueryParameters) StartTime() time.Time
StartTime returns startTime.
func (*QueryParameters) UnauthorizedObjectID ¶ added in v0.6.0
func (p *QueryParameters) UnauthorizedObjectID() string
UnauthorizedObjectID returns unauthorizedObjectID.
func (*QueryParameters) Version ¶
func (p *QueryParameters) Version() string
Version returns version.
type SharedKeyCredential ¶
type SharedKeyCredential = exported.SharedKeyCredential
SharedKeyCredential contains an account's name and its primary or secondary key.
type URLParts ¶
type URLParts struct { Scheme string // Ex: "https://" Host string // Ex: "account.blob.core.windows.net", "10.132.141.33", "10.132.141.33:80" IPEndpointStyleInfo IPEndpointStyleInfo ContainerName string // "" if no container BlobName string // "" if no blob Snapshot string // "" if not a snapshot SAS QueryParameters UnparsedParams string VersionID string // "" if not versioning enabled }
URLParts object represents the components that make up an Azure Storage Container/Blob URL. NOTE: Changing any SAS-related field requires computing a new SAS signature.
type UserDelegationCredential ¶
type UserDelegationCredential = exported.UserDelegationCredential
UserDelegationCredential contains an account's name and its user delegation key.