/
oauth_material.go
69 lines (57 loc) · 1.46 KB
/
oauth_material.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
package client
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"strings"
"github.com/pkg/errors"
)
type oauthMaterial struct {
Nonce string
NonceBytes []byte
State string
StateBytes []byte
CodeVerifier string
CodeChallenge string
}
func newOauthMaterial() (*oauthMaterial, error) {
generateURLSafeRandom := func(numBytes int) (string, error) {
b := make([]byte, numBytes)
_, err := rand.Read(b)
if err != nil {
return "", errors.Wrap(err, "could not read random bytes")
}
return pkceBase64URLEncode(b), nil
}
nonce, err := generateURLSafeRandom(32)
if err != nil {
return nil, err
}
state, err := generateURLSafeRandom(32)
if err != nil {
return nil, err
}
codeVerifier, err := generateURLSafeRandom(64)
if err != nil {
return nil, err
}
codeChallengeBytes := sha256.Sum256([]byte(codeVerifier))
codeChallenge := pkceBase64URLEncode(codeChallengeBytes[:])
return &oauthMaterial{
Nonce: nonce,
NonceBytes: []byte(nonce),
State: state,
StateBytes: []byte(state),
CodeVerifier: codeVerifier,
CodeChallenge: codeChallenge,
}, nil
}
func pkceBase64URLEncode(b []byte) string {
r := base64.URLEncoding.EncodeToString(b)
// https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce
// For some reason have to replace these chars, we lose some entropy but that's ok
r = strings.ReplaceAll(r, "+", "-")
r = strings.ReplaceAll(r, "/", "_")
r = strings.ReplaceAll(r, "=", "")
return r
}