-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresh.go
88 lines (77 loc) · 2.17 KB
/
refresh.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
87
88
package authenticate
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type (
RefreshTokenResponse struct {
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
Resource string `json:"resource"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
)
func (a *activeDirectory) refreshExpiry(refreshToken string) (string, string, int64, error) {
var permissions string
if a.ExtraPermissions == "" {
permissions = "User.Read Group.Read.All offline_access"
} else {
permissions = "User.Read Group.Read.All" + fmt.Sprintf(" %s", a.ExtraPermissions)
}
refreshFormData, err := json.Marshal(&refreshTokenPostJSON{
ClientID: a.ClientID,
Scope: permissions,
Tenant: a.TenantID,
RedirectURI: a.RedirectURI,
GrantType: "refresh_token",
RefreshToken: refreshToken,
ClientSecret: a.ClientSecret,
})
if err != nil {
return "", "", 0, err
}
values := url.Values{}
var data map[string]interface{}
if err := json.Unmarshal(refreshFormData, &data); err != nil {
return "", "", 0, err
}
for key, value := range data {
values.Add(key, value.(string))
}
refreshEndpoint := fmt.Sprintf(accessTokenURI, a.TenantID)
req, err := http.NewRequest("POST", refreshEndpoint, strings.NewReader(values.Encode()))
if err != nil {
return "", "", 0, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(values.Encode())))
httpClient := &http.Client{Timeout: 10 * time.Second}
res, err := httpClient.Do(req)
if err != nil {
return "", "", 0, err
}
byt, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return "", "", 0, err
}
responseData := &accessTokenResponse{}
err = json.Unmarshal(byt, &responseData)
if err != nil {
return "", "", 0, err
}
// Prepare data for refresh
var formData refreshTokenPostJSON
if err := json.Unmarshal(refreshFormData, &formData); err != nil {
return "", "", 0, err
}
formData.RefreshToken = responseData.RefreshToken
return responseData.AccessToken, responseData.RefreshToken, responseData.ExpiresIn, nil
}