...

Source file src/github.com/Azure/go-autorest/autorest/authorization_sas.go

Documentation: github.com/Azure/go-autorest/autorest

     1  package autorest
     2  
     3  // Copyright 2017 Microsoft Corporation
     4  //
     5  //  Licensed under the Apache License, Version 2.0 (the "License");
     6  //  you may not use this file except in compliance with the License.
     7  //  You may obtain a copy of the License at
     8  //
     9  //      http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  //  Unless required by applicable law or agreed to in writing, software
    12  //  distributed under the License is distributed on an "AS IS" BASIS,
    13  //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  //  See the License for the specific language governing permissions and
    15  //  limitations under the License.
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"strings"
    21  )
    22  
    23  // SASTokenAuthorizer implements an authorization for SAS Token Authentication
    24  // this can be used for interaction with Blob Storage Endpoints
    25  type SASTokenAuthorizer struct {
    26  	sasToken string
    27  }
    28  
    29  // NewSASTokenAuthorizer creates a SASTokenAuthorizer using the given credentials
    30  func NewSASTokenAuthorizer(sasToken string) (*SASTokenAuthorizer, error) {
    31  	if strings.TrimSpace(sasToken) == "" {
    32  		return nil, fmt.Errorf("sasToken cannot be empty")
    33  	}
    34  
    35  	token := sasToken
    36  	if strings.HasPrefix(sasToken, "?") {
    37  		token = strings.TrimPrefix(sasToken, "?")
    38  	}
    39  
    40  	return &SASTokenAuthorizer{
    41  		sasToken: token,
    42  	}, nil
    43  }
    44  
    45  // WithAuthorization returns a PrepareDecorator that adds a shared access signature token to the
    46  // URI's query parameters.  This can be used for the Blob, Queue, and File Services.
    47  //
    48  // See https://docs.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature
    49  func (sas *SASTokenAuthorizer) WithAuthorization() PrepareDecorator {
    50  	return func(p Preparer) Preparer {
    51  		return PreparerFunc(func(r *http.Request) (*http.Request, error) {
    52  			r, err := p.Prepare(r)
    53  			if err != nil {
    54  				return r, err
    55  			}
    56  
    57  			if r.URL.RawQuery == "" {
    58  				r.URL.RawQuery = sas.sasToken
    59  			} else if !strings.Contains(r.URL.RawQuery, sas.sasToken) {
    60  				r.URL.RawQuery = fmt.Sprintf("%s&%s", r.URL.RawQuery, sas.sasToken)
    61  			}
    62  
    63  			return Prepare(r)
    64  		})
    65  	}
    66  }
    67  

View as plain text