-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.go
More file actions
257 lines (231 loc) · 6.44 KB
/
auth.go
File metadata and controls
257 lines (231 loc) · 6.44 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package microauth
import (
"crypto/rsa"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"strings"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v5"
)
// Public Key Resource Types
const (
KeyFile int = 0 //public key is retrieved from a file using the provided file path
KeyString = 1 //public key is retrieved as a string from the environment
KeycloakUrl = 2 //Public key is retrieved from keycloak service at the provided url
)
type AuthRouteFunction func(c *echo.Context, store interface{}, roles []int, claims JwtClaim) bool
type AuthMiddlewareFunction func(c *echo.Context, store interface{}, claims JwtClaim) bool
type Auth struct {
//VerifyKey *rsa.PublicKey
VerifyKeys []*rsa.PublicKey
Aud string
AuthRoute AuthRouteFunction
AuthMiddleware AuthMiddlewareFunction
Store interface{}
}
func (a *Auth) AuthorizeMiddleware(handler echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
auth := c.Request().Header.Get(echo.HeaderAuthorization)
tokenString := strings.TrimPrefix(auth, "Bearer ")
claims, err := a.marshalJwt(tokenString)
if err != nil || !Contains_string(claims.Aud, a.Aud) {
log.Print(err)
return echo.NewHTTPError(http.StatusUnauthorized, "bad token")
}
if a.AuthMiddleware != nil && a.AuthMiddleware(c, a.Store, claims) {
return handler(c)
} else {
return echo.NewHTTPError(http.StatusUnauthorized, "")
}
}
}
func (a *Auth) AuthorizeRoute(handler echo.HandlerFunc, roles ...int) echo.HandlerFunc {
return func(c *echo.Context) error {
auth := c.Request().Header.Get(echo.HeaderAuthorization)
tokenString := strings.TrimPrefix(auth, "Bearer ")
return a.authorization(tokenString, handler, c, roles)
}
}
func (a *Auth) AuthorizeForm(handler echo.HandlerFunc, roles ...int) echo.HandlerFunc {
return func(c *echo.Context) error {
tokenString := c.FormValue("authorization")
return a.authorization(tokenString, handler, c, roles)
}
}
func (a *Auth) authorization(tokenString string, handler echo.HandlerFunc, c *echo.Context, roles []int) error {
claims, err := a.marshalJwt(tokenString)
if err != nil || !Contains_string(claims.Aud, a.Aud) {
log.Print(err)
return echo.NewHTTPError(http.StatusUnauthorized, "bad token")
}
if a.AuthRoute != nil && a.AuthRoute(c, a.Store, roles, claims) {
return handler(c)
} else {
return echo.NewHTTPError(http.StatusUnauthorized, "")
}
}
type VerificationKeyOptions struct {
KeySource int
KeyVal string
}
func (a *Auth) LoadVerificationKey(options VerificationKeyOptions) error {
switch options.KeySource {
case KeyString:
return a.SetVerificationKey(options.KeyVal)
case KeyFile:
return a.LoadVerificationKeyFile(options.KeyVal)
case KeycloakUrl:
realmInfo, err := FetchKeycloakRealmInfo(options.KeyVal)
if err != nil {
return err
}
return a.SetVerificationKey(realmInfo.PublicKey)
}
return errors.New("Invalid Public Key Source")
}
func (a *Auth) SetVerificationKey(key string) error {
key = fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", key)
pk, err := jwt.ParseRSAPublicKeyFromPEM([]byte(key))
if err != nil {
return err
}
a.VerifyKeys = append(a.VerifyKeys, pk)
return nil
}
func (a *Auth) LoadVerificationKeyFile(filePath string) error {
publicKeyBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
return a.loadVerificationKey(publicKeyBytes)
}
func (a *Auth) loadVerificationKey(bytes []byte) error {
pk, err := jwt.ParseRSAPublicKeyFromPEM(bytes)
if err != nil {
return err
}
a.VerifyKeys = append(a.VerifyKeys, pk)
return nil
}
func (a *Auth) marshalJwt(tokenString string) (JwtClaim, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return a.VerifyKeys[0], nil
})
if err != nil {
return JwtClaim{}, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
jwtUser := JwtClaim{
Sub: readClaim("sub", claims),
Aud: marshalAud(claims["aud"]),
Roles: readClaimArray(claims["roles"]),
UserName: readClaim("preferred_username", claims),
Email: readClaim("email", claims),
Claims: claims,
}
return jwtUser, nil
} else {
return JwtClaim{}, errors.New("Invalid Token")
}
}
func (a *Auth) LoadVerificationKeys(fieldPath string) error {
files, err := ioutil.ReadDir(fieldPath)
if err != nil {
return err
}
for _, v := range files {
if ext := filepath.Ext(v.Name()); ext == ".pem" {
fmt.Printf("Loading Public Key: %s\n", v.Name())
pk, err := loadKeyFile(fieldPath + "/" + v.Name())
if err != nil {
return err
}
a.VerifyKeys = append(a.VerifyKeys, pk)
}
}
return nil
}
func (a *Auth) marshalJwts(tokenString string) (JwtClaim, error) {
var token *jwt.Token = nil
var err error
for _, verificationKey := range a.VerifyKeys {
token, err = jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return verificationKey, nil
})
if err == nil {
break
}
}
if token == nil {
return JwtClaim{}, errors.New("Invalid Token")
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
jwtUser := JwtClaim{
Sub: readClaim("sub", claims),
Aud: marshalAud(claims["aud"]),
Roles: readClaimArray(claims["roles"]),
UserName: readClaim("preferred_username", claims),
Email: readClaim("email", claims),
Claims: claims,
}
return jwtUser, nil
} else {
return JwtClaim{}, errors.New("Invalid Token")
}
}
func readClaim(claimname string, claims jwt.MapClaims) string {
claim, ok := claims[claimname]
if !ok || claim == nil {
return ""
}
return claim.(string)
}
func loadKeyFile(filePath string) (*rsa.PublicKey, error) {
publicKeyBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
return jwt.ParseRSAPublicKeyFromPEM(publicKeyBytes)
}
func readClaimArray(data interface{}) []string {
a := []string{}
if data != nil {
claimarray := data.([]interface{})
for _, c := range claimarray {
a = append(a, c.(string))
}
}
return a
}
func marshalAud(aud interface{}) []string {
a := []string{}
switch aud.(type) {
case []interface{}:
for _, v := range aud.([]interface{}) {
a = append(a, v.(string))
}
case interface{}:
a = append(a, aud.(string))
}
return a
}
func Contains(a []int, x int) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
func Contains_string(s []string, t string) bool {
for _, n := range s {
if t == n {
return true
}
}
return false
}