Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read a refresh token from accessTokens.json #39

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions authentication/auth_method_azure_cli_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"

"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure/cli"
"github.com/hashicorp/go-multierror"
"github.com/mitchellh/go-homedir"
)

type azureCliTokenAuth struct {
Expand Down Expand Up @@ -161,6 +165,12 @@ func obtainAuthorizationToken(endpoint string, subscriptionId string) (*cli.Toke
return nil, fmt.Errorf("Error parsing json result from the Azure CLI: %v", err)
}

// Currently, Azure CLI does not return the refresh token. Try reading the refresh token from user's disk.
if token.RefreshToken == "" {
// Ignore any error here: we don't want to fail because of no access to the tokens file.
token.RefreshToken, _ = readRefreshTokenFromAccessTokensFile(token.AccessToken)
}

return &token, nil
}

Expand Down Expand Up @@ -193,3 +203,39 @@ func jsonUnmarshalAzCmd(i interface{}, arg ...string) error {

return nil
}

func readRefreshTokenFromAccessTokensFile(accessToken string) (string, error) {
azureConfig := os.Getenv("AZURE_CONFIG_DIR")
if azureConfig == "" {
home, err := homedir.Dir()
if err != nil {
return "", err
}
azureConfig = filepath.Join(home, ".azure")
}
path := filepath.Join(azureConfig, "accessTokens.json")

jsonFile, err := os.Open(path)
if err != nil {
return "", err
}
defer jsonFile.Close()

bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return "", err
}

var tokens []cli.Token
if err := json.Unmarshal(bytes, &tokens); err != nil {
return "", err
}

for _, value := range tokens {
if value.AccessToken == accessToken {
return value.RefreshToken, nil
}
}

return "", nil
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ require (
github.com/Azure/go-autorest/autorest/validation v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/hashicorp/go-multierror v1.0.0
github.com/mitchellh/go-homedir v1.1.0
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2
)