Skip to content

Commit

Permalink
EXPERIMENTAL pkg/env/msiauthorizer.go
Browse files Browse the repository at this point in the history
  • Loading branch information
mbarnes committed Apr 26, 2022
1 parent ebf475f commit f5fdc3a
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions pkg/env/msiauthorizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (
"fmt"
"os"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure/auth"
"github.com/jongio/azidext/go/azidext"
)

type MSIContext string
Expand All @@ -19,27 +21,35 @@ const (
)

func (c *core) NewMSIAuthorizer(msiContext MSIContext, resource string) (autorest.Authorizer, error) {
if !c.IsLocalDevelopmentMode() {
return auth.NewAuthorizerFromEnvironmentWithResource(resource)
}
var tokenCredential azcore.TokenCredential
var err error

for _, key := range []string{
"AZURE_" + string(msiContext) + "_CLIENT_ID",
"AZURE_" + string(msiContext) + "_CLIENT_SECRET",
"AZURE_TENANT_ID",
} {
if _, found := os.LookupEnv(key); !found {
return nil, fmt.Errorf("environment variable %q unset (development mode)", key)
if !c.IsLocalDevelopmentMode() {
tokenCredential, err = azidentity.NewManagedIdentityCredential(
&azidentity.ManagedIdentityCredentialOptions{})
} else {
for _, key := range []string{
"AZURE_" + string(msiContext) + "_CLIENT_ID",
"AZURE_" + string(msiContext) + "_CLIENT_SECRET",
"AZURE_TENANT_ID",
} {
if _, found := os.LookupEnv(key); !found {
return nil, fmt.Errorf("environment variable %q unset (development mode)", key)
}
}
}

config := &auth.ClientCredentialsConfig{
ClientID: os.Getenv("AZURE_" + string(msiContext) + "_CLIENT_ID"),
ClientSecret: os.Getenv("AZURE_" + string(msiContext) + "_CLIENT_SECRET"),
TenantID: os.Getenv("AZURE_TENANT_ID"),
Resource: resource,
AADEndpoint: c.Environment().ActiveDirectoryEndpoint,
tokenCredential, err = azidentity.NewClientSecretCredential(
os.Getenv("AZURE_TENANT_ID"),
os.Getenv("AZURE_"+string(msiContext)+"_CLIENT_ID"),
os.Getenv("AZURE_"+string(msiContext)+"_CLIENT_SECRET"),
&azidentity.ClientSecretCredentialOptions{
AuthorityHost: c.Environment().AuthorityHost,
})
}
if err != nil {
return nil, err
}

return config.Authorizer()
scopes := []string{resource + "/.default"}
return azidext.NewTokenCredentialAdapter(tokenCredential, scopes), nil
}

0 comments on commit f5fdc3a

Please sign in to comment.