This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
forked from apid/goscaffold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
224 lines (193 loc) · 4.9 KB
/
oauth.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package goscaffold
import (
"context"
"crypto/rsa"
"encoding/json"
"net/http"
"sync"
"time"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
)
const params = "params"
// Errors to return
type Errors []string
/*
The SSO key parameters
*/
type ssoKey struct {
Alg string `json:"alg"`
Value string `json:"value"`
Kty string `json:"kty"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
}
/*
oauth provides http an connection to the URL that has the public
key for verifying the JWT token
*/
type oauth struct {
gPkey *rsa.PublicKey
rwMutex *sync.RWMutex
}
/*
ErrorResponse delivers the errors back to the caller, once validation
has failed
*/
type ErrorResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Errors []string `json:"errors"`
}
/*
OAuthService offers interface functions that act on OAuth param,
used to verify JWT tokens for the Http handler functions client
wishes to validate against (via SSOHandler).
*/
type OAuthService interface {
SSOHandler(p string, h func(http.ResponseWriter, *http.Request)) (string, httprouter.Handle)
}
/*
CreateOAuth is a constructor that creates OAuth for OAuthService
interface. OAuthService interface offers method:-
(1) SSOHandler(): Offers the user to attach http handler for JWT
verification.
*/
func (s *HTTPScaffold) CreateOAuth(keyURL string) OAuthService {
pk, _ := getPublicKey(keyURL)
oa := &oauth{
rwMutex: &sync.RWMutex{},
}
oa.setPkSafe(pk)
oa.updatePublicKeysPeriodic(keyURL)
return oa
}
/*
SetParamsInRequest Sets the params and its values in the request
*/
func SetParamsInRequest(r *http.Request, ps httprouter.Params) *http.Request {
newContext := context.WithValue(r.Context(), params, ps)
return r.WithContext(newContext)
}
/*
FetchParams fetches the param values, given the params in the request
*/
func FetchParams(r *http.Request) httprouter.Params {
ctx := r.Context()
return ctx.Value(params).(httprouter.Params)
}
/*
SSOHandler offers the users the flexibility of choosing which http handlers
need JWT validation.
*/
func (a *oauth) SSOHandler(p string, h func(http.ResponseWriter, *http.Request)) (string, httprouter.Handle) {
return p, a.VerifyOAuth(alice.New().ThenFunc(h))
}
/*
VerifyOAuth verifies the JWT token in the request using the public key configured
via CreateOAuth constructor.
*/
func (a *oauth) VerifyOAuth(next http.Handler) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, ps httprouter.Params) {
/* Parse the JWT from the input request */
jwt, err := jws.ParseJWTFromRequest(r)
if err != nil {
WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
return
}
/* Get the pulic key from cache */
pk := a.getPkSafe()
if pk == nil {
WriteErrorResponse(http.StatusBadRequest, "Public key not configured. Validation failed.", rw)
return
}
/* Validate the token */
err = jwt.Validate(pk, crypto.SigningMethodRS256)
if err != nil {
WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
return
}
/* Set the input params in the request */
r = SetParamsInRequest(r, ps)
next.ServeHTTP(rw, r)
}
}
/*
WriteErrorResponse write a non 200 error response
*/
func WriteErrorResponse(statusCode int, message string, w http.ResponseWriter) {
var errstr []string
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
errstr = append(errstr, http.StatusText(statusCode))
resp := ErrorResponse{
Status: http.StatusText(statusCode),
Message: message,
Errors: errstr,
}
json.NewEncoder(w).Encode(resp)
}
/*
updatePulicKeysPeriodic updates the cache periodically (every hour)
*/
func (a *oauth) updatePublicKeysPeriodic(keyURL string) {
ticker := time.NewTicker(time.Hour)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
pk, err := getPublicKey(keyURL)
if err == nil {
a.setPkSafe(pk)
}
case <-quit:
ticker.Stop()
return
}
}
}()
}
/*
getPubicKey: Loads the Public key in to memory and returns it.
*/
func getPublicKey(keyURL string) (*rsa.PublicKey, error) {
/* Connect to the server to fetch Key details */
r, err := http.Get(keyURL)
if err != nil {
return nil, err
}
defer r.Body.Close()
/* Decode the SSO Key */
ssoKey := &ssoKey{}
err = json.NewDecoder(r.Body).Decode(ssoKey)
if err != nil {
return nil, err
}
/* Retrieve the Public Key from SSO Key */
publicKey, err := crypto.ParseRSAPublicKeyFromPEM([]byte(ssoKey.Value))
if err != nil {
return nil, err
}
return publicKey, nil
}
/*
setPkSafe Safely stores the Public Key (via a Write Lock)
*/
func (a *oauth) setPkSafe(pk *rsa.PublicKey) {
a.rwMutex.Lock()
a.gPkey = pk
a.rwMutex.Unlock()
}
/*
getPkSafe returns the stored key (via a read lock)
*/
func (a *oauth) getPkSafe() *rsa.PublicKey {
a.rwMutex.RLock()
pk := a.gPkey
a.rwMutex.RUnlock()
return pk
}