3 // Copyright 2017 Microsoft Corporation
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
24 "github.com/Azure/go-autorest/autorest/adal"
25 "github.com/Azure/go-autorest/tracing"
29 bearerChallengeHeader = "Www-Authenticate"
32 apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key"
33 bingAPISdkHeader = "X-BingApis-SDK-Client"
34 golangBingAPISdkHeaderValue = "Go-SDK"
35 authorization = "Authorization"
39 // Authorizer is the interface that provides a PrepareDecorator used to supply request
40 // authorization. Most often, the Authorizer decorator runs last so it has access to the full
41 // state of the formed HTTP request.
42 type Authorizer interface {
43 WithAuthorization() PrepareDecorator
46 // NullAuthorizer implements a default, "do nothing" Authorizer.
47 type NullAuthorizer struct{}
49 // WithAuthorization returns a PrepareDecorator that does nothing.
50 func (na NullAuthorizer) WithAuthorization() PrepareDecorator {
54 // APIKeyAuthorizer implements API Key authorization.
55 type APIKeyAuthorizer struct {
56 headers map[string]interface{}
57 queryParameters map[string]interface{}
60 // NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers.
61 func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer {
62 return NewAPIKeyAuthorizer(headers, nil)
65 // NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters.
66 func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer {
67 return NewAPIKeyAuthorizer(nil, queryParameters)
70 // NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers.
71 func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer {
72 return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters}
75 // WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Parameters.
76 func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator {
77 return func(p Preparer) Preparer {
78 return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters))
82 // CognitiveServicesAuthorizer implements authorization for Cognitive Services.
83 type CognitiveServicesAuthorizer struct {
84 subscriptionKey string
87 // NewCognitiveServicesAuthorizer is
88 func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer {
89 return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey}
92 // WithAuthorization is
93 func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator {
94 headers := make(map[string]interface{})
95 headers[apiKeyAuthorizerHeader] = csa.subscriptionKey
96 headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue
98 return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization()
101 // BearerAuthorizer implements the bearer authorization
102 type BearerAuthorizer struct {
103 tokenProvider adal.OAuthTokenProvider
106 // NewBearerAuthorizer crates a BearerAuthorizer using the given token provider
107 func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer {
108 return &BearerAuthorizer{tokenProvider: tp}
111 // WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose
112 // value is "Bearer " followed by the token.
114 // By default, the token will be automatically refreshed through the Refresher interface.
115 func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator {
116 return func(p Preparer) Preparer {
117 return PreparerFunc(func(r *http.Request) (*http.Request, error) {
118 r, err := p.Prepare(r)
120 // the ordering is important here, prefer RefresherWithContext if available
121 if refresher, ok := ba.tokenProvider.(adal.RefresherWithContext); ok {
122 err = refresher.EnsureFreshWithContext(r.Context())
123 } else if refresher, ok := ba.tokenProvider.(adal.Refresher); ok {
124 err = refresher.EnsureFresh()
127 var resp *http.Response
128 if tokError, ok := err.(adal.TokenRefreshError); ok {
129 resp = tokError.Response()
131 return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp,
132 "Failed to refresh the Token for request to %s", r.URL)
134 return Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken())))
141 // BearerAuthorizerCallbackFunc is the authentication callback signature.
142 type BearerAuthorizerCallbackFunc func(tenantID, resource string) (*BearerAuthorizer, error)
144 // BearerAuthorizerCallback implements bearer authorization via a callback.
145 type BearerAuthorizerCallback struct {
147 callback BearerAuthorizerCallbackFunc
150 // NewBearerAuthorizerCallback creates a bearer authorization callback. The callback
151 // is invoked when the HTTP request is submitted.
152 func NewBearerAuthorizerCallback(sender Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback {
154 sender = &http.Client{Transport: tracing.Transport}
156 return &BearerAuthorizerCallback{sender: sender, callback: callback}
159 // WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value
160 // is "Bearer " followed by the token. The BearerAuthorizer is obtained via a user-supplied callback.
162 // By default, the token will be automatically refreshed through the Refresher interface.
163 func (bacb *BearerAuthorizerCallback) WithAuthorization() PrepareDecorator {
164 return func(p Preparer) Preparer {
165 return PreparerFunc(func(r *http.Request) (*http.Request, error) {
166 r, err := p.Prepare(r)
168 // make a copy of the request and remove the body as it's not
169 // required and avoids us having to create a copy of it.
171 removeRequestBody(&rCopy)
173 resp, err := bacb.sender.Do(&rCopy)
174 if err == nil && resp.StatusCode == 401 {
175 defer resp.Body.Close()
176 if hasBearerChallenge(resp) {
177 bc, err := newBearerChallenge(resp)
181 if bacb.callback != nil {
182 ba, err := bacb.callback(bc.values[tenantID], bc.values["resource"])
186 return Prepare(r, ba.WithAuthorization())
196 // returns true if the HTTP response contains a bearer challenge
197 func hasBearerChallenge(resp *http.Response) bool {
198 authHeader := resp.Header.Get(bearerChallengeHeader)
199 if len(authHeader) == 0 || strings.Index(authHeader, bearer) < 0 {
205 type bearerChallenge struct {
206 values map[string]string
209 func newBearerChallenge(resp *http.Response) (bc bearerChallenge, err error) {
210 challenge := strings.TrimSpace(resp.Header.Get(bearerChallengeHeader))
211 trimmedChallenge := challenge[len(bearer)+1:]
213 // challenge is a set of key=value pairs that are comma delimited
214 pairs := strings.Split(trimmedChallenge, ",")
216 err = fmt.Errorf("challenge '%s' contains no pairs", challenge)
220 bc.values = make(map[string]string)
221 for i := range pairs {
222 trimmedPair := strings.TrimSpace(pairs[i])
223 pair := strings.Split(trimmedPair, "=")
225 // remove the enclosing quotes
226 key := strings.Trim(pair[0], "\"")
227 value := strings.Trim(pair[1], "\"")
230 case "authorization", "authorization_uri":
231 // strip the tenant ID from the authorization URL
232 asURL, err := url.Parse(value)
236 bc.values[tenantID] = asURL.Path[1:]
238 bc.values[key] = value
246 // EventGridKeyAuthorizer implements authorization for event grid using key authentication.
247 type EventGridKeyAuthorizer struct {
251 // NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer
252 // with the specified topic key.
253 func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer {
254 return EventGridKeyAuthorizer{topicKey: topicKey}
257 // WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header.
258 func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator {
259 headers := map[string]interface{}{
260 "aeg-sas-key": egta.topicKey,
262 return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization()
265 // BasicAuthorizer implements basic HTTP authorization by adding the Authorization HTTP header
266 // with the value "Basic <TOKEN>" where <TOKEN> is a base64-encoded username:password tuple.
267 type BasicAuthorizer struct {
272 // NewBasicAuthorizer creates a new BasicAuthorizer with the specified username and password.
273 func NewBasicAuthorizer(userName, password string) *BasicAuthorizer {
274 return &BasicAuthorizer{
280 // WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose
281 // value is "Basic " followed by the base64-encoded username:password tuple.
282 func (ba *BasicAuthorizer) WithAuthorization() PrepareDecorator {
283 headers := make(map[string]interface{})
284 headers[authorization] = basic + " " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.userName, ba.password)))
286 return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization()