forked from TykTechnologies/tyk-grpc-go-basicauth-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
157 lines (130 loc) · 3.76 KB
/
main.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
package main
import (
"context"
"encoding/base64"
"net"
"net/http"
"strings"
"time"
"github.com/TykTechnologies/tyk-protobuf/bindings/go"
"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc"
)
const (
listenAddress = ":9111"
jwtHmacSharedSecret = "foobarbaz"
)
var (
// user:pass
userDB = map[string][]byte{}
policiesToApply = []string{
"5d3f3c603f03d3d66fbfad77",
}
)
func init() {
var pass []byte
var err error
// bootstrapping the user DB
pass, err = bcrypt.GenerateFromPassword([]byte("bar"), 10)
fatalOnError(err, "unable to bootstrap db")
userDB["foo"] = pass
pass, err = bcrypt.GenerateFromPassword([]byte("baz"), 10)
fatalOnError(err, "unable to bootstrap db")
userDB["bar"] = pass
}
func main() {
lis, err := net.Listen("tcp", listenAddress)
fatalOnError(err, "failed to start tcp listener")
logrus.Infof("starting grpc middleware on %s", listenAddress)
s := grpc.NewServer()
coprocess.RegisterDispatcherServer(s, &Dispatcher{})
fatalOnError(s.Serve(lis), "unable to start grpc middleware")
}
type Dispatcher struct{}
func (d *Dispatcher) Dispatch(ctx context.Context, object *coprocess.Object) (*coprocess.Object, error) {
switch object.HookName {
case "Login":
println("calling LoginHook")
return LoginHook(object)
}
logrus.Warnf("unknown hook: %v", object.HookName)
return object, nil
}
func (d *Dispatcher) DispatchEvent(ctx context.Context, event *coprocess.Event) (*coprocess.EventReply, error) {
return &coprocess.EventReply{}, nil
}
func LoginHook(object *coprocess.Object) (*coprocess.Object, error) {
authKey := object.Request.Headers["Authorization"]
un, pw, found := parseBasicAuth(authKey)
if !found {
return failAuth(object, "credentials not present")
}
// REPLACE WITH CUSTOM LOGIC
realPass, userExists := userDB[un]
if !userExists {
return failAuth(object, "user not in DB")
}
if err := bcrypt.CompareHashAndPassword(realPass, []byte(pw)); err != nil {
return failAuth(object, "wrong password")
}
// /REPLACE WITH CUSTOM LOGIC
jot, err := generateJWT(un)
if err != nil {
println("error generating jwt", err.Error())
object.Request.ReturnOverrides.ResponseError = "middleware error"
object.Request.ReturnOverrides.ResponseCode = http.StatusInternalServerError
return object, nil
}
// Set the ID extractor deadline, useful for caching valid keys:
extractorDeadline := time.Now().Add(time.Minute).Unix()
object.Session = &coprocess.SessionState{
Rate: 0,
Per: 1.0,
QuotaMax: int64(0),
QuotaRenews: time.Now().Unix(),
IdExtractorDeadline: extractorDeadline,
Metadata: map[string]string{
"jwt": jot,
"token": un,
},
ApplyPolicies: policiesToApply,
}
return object, nil
}
func parseBasicAuth(auth string) (username, password string, ok bool) {
const prefix = "Basic "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
func generateJWT(username string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = &jwt.StandardClaims{
Subject: username,
IssuedAt: time.Now().Unix(),
}
return token.SignedString([]byte(jwtHmacSharedSecret))
}
func fatalOnError(err error, msg string) {
if err != nil {
logrus.WithError(err).Fatal(msg)
}
}
func failAuth(object *coprocess.Object, msg string) (*coprocess.Object, error) {
object.Request.ReturnOverrides.ResponseCode = http.StatusForbidden
object.Request.ReturnOverrides.ResponseError = msg
return object, nil
}