-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_certificate_strategy.go
109 lines (86 loc) · 2.39 KB
/
tls_certificate_strategy.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
package auth
import (
"bytes"
"crypto/md5"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/lcoutinho/luizalabs-client-api/config"
"github.com/patrickmn/go-cache"
"log"
"time"
)
type TlsJwtAuth struct {
memoryCacheClient *cache.Cache
}
func (sv *TlsJwtAuth) SetCacheProvider(cacheClient *cache.Cache) {
sv.memoryCacheClient = cacheClient
}
func (sv *TlsJwtAuth) GenerateToken(resource string) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Add(config.JWT_TIME_EXPIRE).Unix()
claims["resource"] = resource
token.Claims = claims
signingKey, _ := sv.generateTls()
tokenString, err := token.SignedString(signingKey)
if err != nil {
panic(err)
}
finalToken := fmt.Sprintf("%s", tokenString)
keyMemory := sv.getMD5Hash(finalToken)
sv.memoryCacheClient.Set(keyMemory, string(signingKey), config.JWT_TIME_EXPIRE)
return fmt.Sprintf("%s", tokenString)
}
func (sv *TlsJwtAuth) ValidateToken(token string) (*jwt.Token, error) {
keyMemory := sv.getMD5Hash(token)
signingKey, found := sv.memoryCacheClient.Get(keyMemory)
if !found {
return nil, errors.New("Invalid token")
}
return jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(signingKey.(string)), nil
})
}
func (sv *TlsJwtAuth) generateTls() ([]byte, []byte) {
var (
err error
privKey *rsa.PrivateKey
pubKey *rsa.PublicKey
pubKeyBytes []byte
)
privKey, err = rsa.GenerateKey(cryptorand.Reader, 2048)
if err != nil {
log.Fatal("Error generating private key")
}
pubKey = &privKey.PublicKey
var privPEMBlock = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privKey),
}
privKeyPEMBuffer := new(bytes.Buffer)
pem.Encode(privKeyPEMBuffer, privPEMBlock)
signingKey := privKeyPEMBuffer.Bytes()
pubKeyBytes, err = x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
log.Fatal("Error marshalling public key")
}
var pubPEMBlock = &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: pubKeyBytes,
}
pubKeyPEMBuffer := new(bytes.Buffer)
pem.Encode(pubKeyPEMBuffer, pubPEMBlock)
verificationKey := pubKeyPEMBuffer.Bytes()
return signingKey, verificationKey
}
func (sv *TlsJwtAuth) getMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}