github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/auth/token_provider.go (about) 1 /* 2 * Copyright 2020 The Compass Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package auth 18 19 import ( 20 "context" 21 22 httputils "github.com/kyma-incubator/compass/components/system-broker/pkg/http" 23 "github.com/kyma-incubator/compass/components/system-broker/pkg/oauth" 24 "github.com/pkg/errors" 25 ) 26 27 // TokenAuthorizationProvider presents a AuthorizationProvider implementation which crafts OAuth Bearer token values for the Authorization header 28 type tokenAuthorizationProvider struct { 29 httpClient httputils.Client 30 } 31 32 // NewTokenAuthorizationProvider constructs an TokenAuthorizationProvider 33 func NewTokenAuthorizationProvider(httpClient httputils.Client) *tokenAuthorizationProvider { 34 return &tokenAuthorizationProvider{ 35 httpClient: httpClient, 36 } 37 } 38 39 // Name specifies the name of the AuthorizationProvider 40 func (u tokenAuthorizationProvider) Name() string { 41 return "TokenAuthorizationProvider" 42 } 43 44 // Matches contains the logic for matching the AuthorizationProvider 45 func (u tokenAuthorizationProvider) Matches(ctx context.Context) bool { 46 credentials, err := LoadFromContext(ctx) 47 if err != nil { 48 return false 49 } 50 51 return credentials.Type() == OAuthCredentialType 52 } 53 54 // GetAuthorization crafts an OAuth Bearer token to inject as part of the executing request 55 func (u tokenAuthorizationProvider) GetAuthorization(ctx context.Context) (string, error) { 56 credentials, err := LoadFromContext(ctx) 57 if err != nil { 58 return "", err 59 } 60 61 oAuthCredentials, ok := credentials.Get().(*OAuthCredentials) 62 if !ok { 63 return "", errors.New("failed to cast credentials to oauth credentials type") 64 } 65 66 token, err := oauth.GetAuthorizationToken(ctx, u.httpClient, oauth.Credentials{ 67 ClientID: oAuthCredentials.ClientID, 68 ClientSecret: oAuthCredentials.ClientSecret, 69 TokenURL: oAuthCredentials.TokenURL, 70 }, oAuthCredentials.Scopes, oAuthCredentials.AdditionalHeaders) 71 if err != nil { 72 return "", err 73 } 74 75 return "Bearer " + token.AccessToken, nil 76 }