-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
access_token.go
55 lines (45 loc) · 1.43 KB
/
access_token.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
package authentication
import (
"fmt"
"log"
"strings"
"time"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure/cli"
)
type AccessToken struct {
ClientID string
AccessToken *adal.Token
IsCloudShell bool
}
func findValidAccessTokenForTenant(tokens []cli.Token, tenantId string) (*AccessToken, error) {
for _, accessToken := range tokens {
token, err := accessToken.ToADALToken()
if err != nil {
return nil, fmt.Errorf("[DEBUG] Error converting access token to token: %+v", err)
}
expirationDate, err := cli.ParseExpirationDate(accessToken.ExpiresOn)
if err != nil {
return nil, fmt.Errorf("Error parsing expiration date: %q", accessToken.ExpiresOn)
}
if expirationDate.UTC().Before(time.Now().UTC()) {
log.Printf("[DEBUG] Token %q has expired", token.AccessToken)
continue
}
if !strings.Contains(accessToken.Resource, "management") {
log.Printf("[DEBUG] Resource %q isn't a management domain", accessToken.Resource)
continue
}
if !strings.HasSuffix(accessToken.Authority, tenantId) {
log.Printf("[DEBUG] Resource %q isn't for the correct Tenant", accessToken.Resource)
continue
}
validAccessToken := AccessToken{
ClientID: accessToken.ClientID,
AccessToken: &token,
IsCloudShell: accessToken.RefreshToken == "",
}
return &validAccessToken, nil
}
return nil, fmt.Errorf("No Access Token was found for the Tenant ID %q", tenantId)
}