-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcredential.go
More file actions
97 lines (76 loc) · 2.47 KB
/
credential.go
File metadata and controls
97 lines (76 loc) · 2.47 KB
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
87
88
89
90
91
92
93
94
95
96
97
package azureclient
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type RefreshTokenCredential struct {
clientID string
clientSecret string
refreshToken string
tenantID string
}
func NewRefreshTokenCredential(ctx context.Context,
tenantID, clientID, clientSecret, refreshToken string,
) (*RefreshTokenCredential, error) {
c := &RefreshTokenCredential{
clientID: clientID,
clientSecret: clientSecret,
tenantID: tenantID,
refreshToken: refreshToken,
}
return c, nil
}
func (c *RefreshTokenCredential) GetToken(ctx context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error) {
accessToken := azcore.AccessToken{}
url := "https://login.microsoftonline.com/" + c.tenantID + "/oauth2/v2.0/token"
data := fmt.Sprintf("grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s",
c.clientID, c.clientSecret, c.refreshToken)
payload := strings.NewReader(data)
// create the request and execute it
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, payload)
if err != nil {
return accessToken, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
return accessToken, err
}
// process the response
defer res.Body.Close()
var responseData map[string]any
body, _ := io.ReadAll(res.Body)
// unmarshal the json into a string map
if err := json.Unmarshal(body, &responseData); err != nil {
return accessToken, err
}
// check for error
if responseData["error_description"] != nil {
errorMessage, ok := responseData["error_description"].(string)
if !ok {
return accessToken, status.Error(codes.InvalidArgument, "failed to get error description")
}
return accessToken, status.Error(codes.InvalidArgument, errorMessage)
}
// retrieve the access token and expiration
token, ok := responseData["access_token"].(string)
if !ok {
return accessToken, status.Error(codes.InvalidArgument, "'access_token' must be a string")
}
accessToken.Token = token
expiresIn, ok := responseData["expires_in"].(float64)
if !ok {
return accessToken, status.Error(codes.InvalidArgument, "'exprires_in' must be a float")
}
accessToken.ExpiresOn = time.Now().Add(time.Second * time.Duration(int(expiresIn)))
return accessToken, nil
}