-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
190 lines (158 loc) · 4.76 KB
/
auth.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
package auth
import (
"encoding/json"
"errors"
"fmt"
"net/http"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
"github.com/form3tech-oss/jwt-go"
)
// Response holds the response message.
type Response struct {
Message string `json:"message"`
}
// Jwks holds a list of json web keys.
type Jwks struct {
Keys []JSONWebKeys `json:"keys"`
}
// JSONWebKeys holds fields related to the JSON Web Key Set for this API.
type JSONWebKeys struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
X5c []string `json:"x5c"`
}
// UserPermission is the data used in HasPermission.
type UserPermission struct {
Request *http.Request
Permission string
}
// UserValidation is the data used in ValidUser.
type UserValidation struct {
Request *http.Request
Permission string
Identifier string
Key string
}
// GetJwtMiddleware returns the Auth0 middleware used to handle authorized endpoints.
func GetJwtMiddleware(audience, issuer string) *jwtmiddleware.JWTMiddleware {
return jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
aud := token.Claims.(jwt.MapClaims)["aud"].([]interface{})
s := make([]string, len(aud))
for i, v := range aud {
s[i] = fmt.Sprint(v)
}
token.Claims.(jwt.MapClaims)["aud"] = s
checkAud := token.Claims.(jwt.MapClaims).VerifyAudience(audience, false)
if !checkAud {
return token, errors.New("Invalid audience")
}
checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(issuer, false)
if !checkIss {
return token, errors.New("invalid issuer")
}
cert, err := getPemCert(token, issuer)
if err != nil {
panic(err.Error())
}
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
return result, nil
},
SigningMethod: jwt.SigningMethodRS256,
})
}
func getPemCert(token *jwt.Token, issuer string) (string, error) {
cert := ""
resp, err := http.Get(fmt.Sprintf("%s.well-known/jwks.json", issuer))
if err != nil {
return cert, err
}
defer resp.Body.Close()
var jwks = Jwks{}
err = json.NewDecoder(resp.Body).Decode(&jwks)
if err != nil {
return cert, err
}
for k := range jwks.Keys {
if token.Header["kid"] == jwks.Keys[k].Kid {
cert = "-----BEGIN CERTIFICATE-----\n" + jwks.Keys[k].X5c[0] + "\n-----END CERTIFICATE-----"
}
}
if cert == "" {
err := errors.New("unable to find appropriate key")
return cert, err
}
return cert, nil
}
// HasPermission confirms the requester has the correct permission to complete the action.
var HasPermission = func(up UserPermission) (bool, error) {
permissions, err := getPermissions(up.Request)
if err != nil {
return false, err
}
return permissionPresent(permissions, up.Permission), nil
}
// ValidUser confirms the requester is either making changes to their own data or has the correct permission to complete the action.
var ValidUser = func(uv UserValidation) (int, error) {
if matchingUser, err := matchingUser(uv.Request, uv.Identifier, uv.Key); err != nil {
return http.StatusInternalServerError, err
} else if !matchingUser {
up := UserPermission{
Request: uv.Request,
Permission: uv.Permission,
}
if hasPermission, err := HasPermission(up); err != nil {
return http.StatusInternalServerError, err
} else if !hasPermission {
return http.StatusUnauthorized, errors.New("missing or invalid permissions")
}
}
return 200, nil
}
func getPermissions(request *http.Request) ([]interface{}, error) {
token, _, err := parseToken(request)
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
return claims["permissions"].([]interface{}), nil
}
return nil, errors.New("failed to parse claims from token")
}
func parseToken(request *http.Request) (*jwt.Token, []string, error) {
header := request.Header.Get("Authorization")
if len(header) < 8 {
return nil, nil, errors.New("token missing or invalid length")
}
tokenString := header[7:]
parser := new(jwt.Parser)
return parser.ParseUnverified(tokenString, jwt.MapClaims{})
}
func permissionPresent(permissions []interface{}, target string) bool {
for _, permission := range permissions {
if permission == target {
return true
}
}
return false
}
var matchingUser = func(request *http.Request, identifier string, target string) (bool, error) {
identifier, err := getIdentifier(request, identifier)
if err != nil {
return false, err
}
return identifier == target, nil
}
func getIdentifier(request *http.Request, identifier string) (string, error) {
token, _, err := parseToken(request)
if err != nil {
return "", err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
return fmt.Sprint(claims[identifier]), nil
}
return "", errors.New("failed to parse claims from token")
}