-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth_middleware.go
192 lines (176 loc) · 5.93 KB
/
auth_middleware.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
package auth
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/legacy"
"github.com/gorilla/sessions"
"github.com/jiaozifs/jiaozifs/auth/crypt"
"github.com/jiaozifs/jiaozifs/models"
)
const (
TokenSessionKeyName = "token"
InternalAuthSessionName = "internal_auth_session"
IDTokenClaimsSessionKey = "id_token_claims"
)
var (
ErrFailedToAccessStorage = errors.New("failed to access storage")
ErrAuthenticatingRequest = errors.New("error authenticating request")
ErrInvalidAPIEndpoint = errors.New("invalid API endpoint")
ErrRequestSizeExceeded = errors.New("request size exceeded")
ErrStorageNamespaceInUse = errors.New("storage namespace already in use")
)
// extractSecurityRequirements using Swagger returns an array of security requirements set for the request.
func extractSecurityRequirements(router routers.Router, r *http.Request) (openapi3.SecurityRequirements, error) {
// Find route
route, _, err := router.FindRoute(r)
if err != nil {
return nil, err
}
if route.Operation.Security == nil {
return route.Spec.Security, nil
}
return *route.Operation.Security, nil
}
type CookieAuthConfig struct {
ValidateIDTokenClaims map[string]string
DefaultInitialGroups []string
InitialGroupsClaimName string
FriendlyNameClaimName string
ExternalUserIDClaimName string
AuthSource string
}
func Middleware(swagger *openapi3.T, authenticator Authenticator, secretStore crypt.SecretStore, userRepo models.IUserRepo, sessionStore sessions.Store) func(next http.Handler) http.Handler {
router, err := legacy.NewRouter(swagger)
if err != nil {
panic(err)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// if request already authenticated
if _, userNotFoundErr := GetOperator(r.Context()); userNotFoundErr == nil {
next.ServeHTTP(w, r)
return
}
securityRequirements, err := extractSecurityRequirements(router, r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(err.Error()))
return
}
user, err := checkSecurityRequirements(r, securityRequirements, authenticator, sessionStore, secretStore, userRepo)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(err.Error()))
return
}
if user != nil {
r = r.WithContext(WithOperator(r.Context(), user))
}
next.ServeHTTP(w, r)
})
}
}
// checkSecurityRequirements goes over the security requirements and check the authentication. returns the user information and error if the security check was required.
// it will return nil user and error in case of no security checks to match.
func checkSecurityRequirements(r *http.Request,
securityRequirements openapi3.SecurityRequirements,
authenticator Authenticator,
sessionStore sessions.Store,
secretStore crypt.SecretStore,
userRepo models.IUserRepo,
) (*models.User, error) {
ctx := r.Context()
var user *models.User
var err error
for _, securityRequirement := range securityRequirements {
for provider := range securityRequirement {
switch provider {
case "jwt_token":
// validate jwt token from header
authHeaderValue := r.Header.Get("Authorization")
if authHeaderValue == "" {
continue
}
parts := strings.Fields(authHeaderValue)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
continue
}
token := parts[1]
user, err = userByToken(ctx, userRepo, secretStore.SharedSecret(), token)
case "basic_auth":
// validate using basic auth
accessKey, secretKey, ok := r.BasicAuth()
if !ok {
continue
}
user, err = userByAuth(ctx, authenticator, userRepo, accessKey, secretKey)
case "cookie_auth":
var internalAuthSession *sessions.Session
internalAuthSession, _ = sessionStore.Get(r, InternalAuthSessionName)
token := ""
if internalAuthSession != nil {
token, _ = internalAuthSession.Values[TokenSessionKeyName].(string)
}
if token == "" {
continue
}
user, err = userByToken(ctx, userRepo, secretStore.SharedSecret(), token)
default:
// unknown security requirement to check
log.With("provider", provider).Error("Authentication middleware unknown security requirement provider")
return nil, ErrAuthenticatingRequest
}
if err != nil {
return nil, err
}
if user != nil {
return user, nil
}
}
}
return nil, nil
}
func userByToken(ctx context.Context, userRepo models.IUserRepo, secret []byte, tokenString string) (*models.User, error) {
claims, err := VerifyToken(secret, tokenString)
if err != nil {
return nil, ErrAuthenticatingRequest
}
// make sure no audience is set for login token
validator := jwt.NewValidator(jwt.WithAudience(LoginAudience))
if err = validator.Validate(claims); err != nil {
return nil, fmt.Errorf("invalid token: %s %w", err, ErrAuthenticatingRequest)
}
username, err := claims.GetSubject()
if err != nil {
return nil, err
}
userData, err := userRepo.Get(ctx, models.NewGetUserParams().SetName(username))
if err != nil {
log.With(
"token", tokenString,
"username", username,
"subject", username,
).Debugf("could not find user id by credentials %v", err)
return nil, ErrAuthenticatingRequest
}
return userData, nil
}
func userByAuth(ctx context.Context, authenticator Authenticator, userRepo models.IUserRepo, accessKey string, secretKey string) (*models.User, error) {
username, err := authenticator.AuthenticateUser(ctx, accessKey, secretKey)
if err != nil {
log.With("user", accessKey).Errorf("authenticate %v", err)
return nil, ErrAuthenticatingRequest
}
user, err := userRepo.Get(ctx, models.NewGetUserParams().SetName(username))
if err != nil {
log.With("user_name", username).Debugf("could not find user id by credentials %s", err)
return nil, ErrAuthenticatingRequest
}
return user, nil
}