-
Notifications
You must be signed in to change notification settings - Fork 92
/
msi.go
86 lines (76 loc) · 2.31 KB
/
msi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package token
import (
"context"
"errors"
"fmt"
"github.com/Azure/go-autorest/autorest/adal"
)
type managedIdentityToken struct {
clientID string
identityResourceID string
resourceID string
}
func newManagedIdentityToken(clientID, identityResourceID, resourceID string) (TokenProvider, error) {
if resourceID == "" {
return nil, errors.New("resourceID cannot be empty")
}
provider := &managedIdentityToken{
clientID: clientID,
identityResourceID: identityResourceID,
resourceID: resourceID,
}
return provider, nil
}
func (p *managedIdentityToken) Token(ctx context.Context) (adal.Token, error) {
var (
spt *adal.ServicePrincipalToken
err error
emptyToken adal.Token
)
callback := func(t adal.Token) error {
return nil
}
// there are multiple options to login with MSI: https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http
// 1. use clientId if present
// 2. use identityResourceID if present
// 3. IMDS default
if p.clientID == "" {
if p.identityResourceID == "" {
// no identity specified, use whatever IMDS default to
spt, err = adal.NewServicePrincipalTokenFromManagedIdentity(
p.resourceID,
nil,
callback)
if err != nil {
return emptyToken, fmt.Errorf("failed to create service principal from managed identity for token refresh: %s", err)
}
} else {
// use a specified managedIdentity resource id
spt, err = adal.NewServicePrincipalTokenFromManagedIdentity(
p.resourceID,
&adal.ManagedIdentityOptions{
IdentityResourceID: p.identityResourceID,
},
callback)
if err != nil {
return emptyToken, fmt.Errorf("failed to create service principal from managed identity with identityResourceID %s for token refresh: %s", p.identityResourceID, err)
}
}
} else {
// use a specified clientId
spt, err = adal.NewServicePrincipalTokenFromManagedIdentity(
p.resourceID,
&adal.ManagedIdentityOptions{
ClientID: p.clientID,
},
callback)
if err != nil {
return emptyToken, fmt.Errorf("failed to create service principal from managed identity %s for token refresh: %s", p.clientID, err)
}
}
err = spt.RefreshWithContext(ctx)
if err != nil {
return emptyToken, err
}
return spt.Token(), nil
}