Skip to content

Commit

Permalink
Add support for AZURE_FEDERATED_TOKEN_FILE
Browse files Browse the repository at this point in the history
This is needed for Azure Workload Identity
  • Loading branch information
Tolsto authored and chrismellard committed Mar 4, 2023
1 parent fb78997 commit 82a0ddb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ AZURE_FEDERATED_TOKEN=<federatedJWT>
AZURE_TENANT_ID=<tenantId>
```

If you use federated OIDC with [Azure Workload Identity](https://github.com/Azure/azure-workload-identity) you don't
have to set any ENVs as they will get injected automatically.

If the above are not set then authentication falls back to managed service identities and the MSI endpoint is
attempted to be contacted which will work in various Azure contexts such as App Service and Azure Kubernetes Service
where the MSI endpoint will authenticate the MSI context the service is running under.
23 changes: 21 additions & 2 deletions pkg/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ func getServicePrincipalToken(settings auth.EnvironmentSettings, resource string
}

// federated OIDC JWT assertion
if jwt, isPresent := os.LookupEnv("AZURE_FEDERATED_TOKEN"); isPresent {
jwt, err := jwtLookup()
if err == nil {
clientID, isPresent := os.LookupEnv("AZURE_CLIENT_ID")
if !isPresent {
return &adal.ServicePrincipalToken{}, fmt.Errorf("failed to get client id from environment")
Expand All @@ -79,11 +80,29 @@ func getServicePrincipalToken(settings auth.EnvironmentSettings, resource string
return &adal.ServicePrincipalToken{}, fmt.Errorf("failed to initialise OAuthConfig - %w", err)
}

return adal.NewServicePrincipalTokenFromFederatedToken(*oAuthConfig, clientID, jwt, resource)
return adal.NewServicePrincipalTokenFromFederatedToken(*oAuthConfig, clientID, *jwt, resource)
}

// 4. MSI
return adal.NewServicePrincipalTokenFromManagedIdentity(resource, &adal.ManagedIdentityOptions{
ClientID: os.Getenv("AZURE_CLIENT_ID"),
})
}

func jwtLookup() (*string, error) {
jwt, isPresent := os.LookupEnv("AZURE_FEDERATED_TOKEN")
if isPresent {
return &jwt, nil
}

if jwtFile, isPresent := os.LookupEnv("AZURE_FEDERATED_TOKEN_FILE"); isPresent {
jwtBytes, err := os.ReadFile(jwtFile)
if err != nil {
return nil, err
}
jwt = string(jwtBytes)
return &jwt, nil
}

return nil, fmt.Errorf("no JWT found")
}

0 comments on commit 82a0ddb

Please sign in to comment.