forked from michivip/skypeapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication.go
193 lines (179 loc) · 5.81 KB
/
authentication.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package bfapi
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"net/http"
"strings"
"time"
)
type OpenIdDocument struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
JwksURI string `json:"jwks_uri"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
}
type SigningKeys struct {
Keys []struct {
Kty string `json:"kty"`
Use string `json:"use"`
KeyId string `json:"kid"`
X5T string `json:"x5t"`
N string `json:"n"`
E string `json:"e"`
X5C []string `json:"x5c"`
Endorsements []string `json:"endorsements,omitempty"`
} `json:"keys"`
}
type JwtHeader struct {
Type string `json:"typ"`
Algorithm string `json:"alg"`
SigningKeyId string `json:"kid"`
SigningKeyIdX5T string `json:"x5t"`
}
type JwtPayload struct {
ServiceUrl string `json:"serviceurl"`
Issuer string `json:"iss"`
Audience string `json:"aud"`
Expires int `json:"exp"`
CreatedOnNbf int `json:"nbf"`
}
type MicrosoftJsonWebToken struct {
HeaderBase64, PayloadBase64 string
Header JwtHeader
Payload JwtPayload
VerifySignature []byte
}
func (microSoftJsonWebToken MicrosoftJsonWebToken) Verify(microsoftAppId string, signingKeys SigningKeys) bool {
if microSoftJsonWebToken.Payload.Issuer != IssuerUrl {
return false
} else if microSoftJsonWebToken.Payload.Audience != microsoftAppId {
return false
} else if int64(microSoftJsonWebToken.Payload.Expires) <= time.Now().Unix() {
return false
} else {
return microSoftJsonWebToken.verifyCertificate(signingKeys)
}
}
func GetSigningKeys() (SigningKeys, error) {
openIdDocument := &OpenIdDocument{}
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, OpenIdRequestPath, nil)
if err != nil {
return SigningKeys{}, err
} else {
resp, err := client.Do(req)
if err != nil {
return SigningKeys{}, err
} else {
defer resp.Body.Close()
err := json.NewDecoder(resp.Body).Decode(openIdDocument)
if err != nil {
return SigningKeys{}, err
} else {
return GetSigningKeysByUrl(openIdDocument.JwksURI)
}
}
}
}
func GetSigningKeysByUrl(url string) (SigningKeys, error) {
signingKeys := &SigningKeys{}
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return SigningKeys{}, err
} else {
resp, err := client.Do(req)
if err != nil {
return SigningKeys{}, err
} else {
defer resp.Body.Close()
err := json.NewDecoder(resp.Body).Decode(signingKeys)
if err != nil {
return SigningKeys{}, err
} else {
return *signingKeys, nil
}
}
}
}
func (microSoftJsonWebToken MicrosoftJsonWebToken) verifyCertificate(signingKeys SigningKeys) bool {
for _, key := range signingKeys.Keys {
if key.KeyId == microSoftJsonWebToken.Header.SigningKeyId {
certificateParsed := parseCertificateString(key.X5C[0])
block, _ := pem.Decode([]byte(certificateParsed))
if certificate, err := x509.ParseCertificate(block.Bytes); err != nil {
return false
} else {
hashed := []byte(microSoftJsonWebToken.HeaderBase64 + SplitCharacter + microSoftJsonWebToken.PayloadBase64)
return certificate.CheckSignature(x509.SHA256WithRSA, hashed, microSoftJsonWebToken.VerifySignature) == nil
}
}
}
return false
}
func parseCertificateString(rawCertificate string) string {
parsedCertificate := "-----BEGIN CERTIFICATE-----\n"
buffer := bytes.NewBuffer(make([]byte, 64))
buffer.Reset()
for index, charByte := range []byte(rawCertificate) {
buffer.WriteByte(charByte)
if (index+1)%64 == 0 {
parsedCertificate += string(buffer.Bytes()) + "\n"
buffer.Reset()
}
}
parsedCertificate += string(buffer.Bytes()) + "\n-----END CERTIFICATE-----"
buffer.Reset()
return parsedCertificate
}
func ParseMicrosoftJsonWebToken(headerValue string) (MicrosoftJsonWebToken, error) {
microsoftJsonWebToken := &MicrosoftJsonWebToken{}
parsedHeaderValue := parseHeaderValue(headerValue)
if len(parsedHeaderValue) == 0 {
return *microsoftJsonWebToken, fmt.Errorf(WrongAuthorizationHeaderFormatError, parsedHeaderValue)
} else {
var split []string = strings.Split(parsedHeaderValue, SplitCharacter)
if len(split) == 3 {
jwtHeader := &JwtHeader{}
jwtPayload := &JwtPayload{}
if err := decodeBase64JsonPart(split[0], jwtHeader); err != nil {
return *microsoftJsonWebToken, err
}
if err := decodeBase64JsonPart(split[1], jwtPayload); err != nil {
return *microsoftJsonWebToken, err
}
jwtVerifySignature, err := base64.RawURLEncoding.DecodeString(split[2])
if err != nil {
return *microsoftJsonWebToken, err
}
microsoftJsonWebToken.HeaderBase64 = split[0]
microsoftJsonWebToken.PayloadBase64 = split[1]
microsoftJsonWebToken.Header = *jwtHeader
microsoftJsonWebToken.Payload = *jwtPayload
microsoftJsonWebToken.VerifySignature = jwtVerifySignature
return *microsoftJsonWebToken, nil
} else {
return *microsoftJsonWebToken, fmt.Errorf(WrongSplitLengthError, SplitCharacter, len(split), parseHeaderValue)
}
}
}
func decodeBase64JsonPart(rawPart string, partObj interface{}) error {
if partBytes, err := base64.RawURLEncoding.DecodeString(rawPart); err != nil {
return err
} else {
return json.NewDecoder(bytes.NewReader(partBytes)).Decode(&partObj)
}
}
func parseHeaderValue(headerValue string) string {
if index := strings.Index(headerValue, AuthorizationHeaderValuePrefix); index == 0 &&
len(headerValue) > len(AuthorizationHeaderValuePrefix) {
return headerValue[len(AuthorizationHeaderValuePrefix):]
} else {
return ""
}
}