3
0

Fix auth flow, allow case with missing JWT

This commit is contained in:
Denis Arh
2019-05-13 18:29:34 +02:00
parent 70dcc3300a
commit 6a5e5dead2
3 changed files with 24 additions and 20 deletions

View File

@@ -68,28 +68,32 @@ func (t *token) Encode(identity Identifiable) string {
func (t *token) Authenticator() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get claims
_, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
resputil.JSON(w, err)
}
jwt, claims, err := jwtauth.FromContext(r.Context())
identity := &Identity{}
if userID, ok := claims["userID"].(string); ok && len(userID) >= 0 {
identity.id, _ = strconv.ParseUint(userID, 10, 64)
}
if memberOf, ok := claims["memberOf"].(string); ok && len(memberOf) >= 0 {
ss := strings.Split(memberOf, " ")
identity.memberOf = make([]uint64, len(ss))
for i, s := range ss {
identity.memberOf[i], _ = strconv.ParseUint(s, 10, 64)
// When token is present, expect no errors and valid claims!
if jwt != nil {
if err != nil {
// But if token is present, the shouldn't be an error
resputil.JSON(w, err)
return
}
identity := &Identity{}
if userID, ok := claims["userID"].(string); ok && len(userID) >= 0 {
identity.id, _ = strconv.ParseUint(userID, 10, 64)
}
if memberOf, ok := claims["memberOf"].(string); ok && len(memberOf) >= 0 {
ss := strings.Split(memberOf, " ")
identity.memberOf = make([]uint64, len(ss))
for i, s := range ss {
identity.memberOf[i], _ = strconv.ParseUint(s, 10, 64)
}
}
r = r.WithContext(SetIdentityToContext(r.Context(), identity))
}
r = r.WithContext(SetIdentityToContext(r.Context(), identity))
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}

View File

@@ -54,6 +54,7 @@ func (ctrl *Auth) Check(ctx context.Context, r *request.AuthCheck) (interface{},
if err = svc.LoadRoleMemberships(user); err != nil {
resputil.JSON(w, err)
return
} else {
resputil.JSON(w, checkResponse{
JWT: ctrl.tokenEncoder.Encode(user),
@@ -65,7 +66,7 @@ func (ctrl *Auth) Check(ctx context.Context, r *request.AuthCheck) (interface{},
}
}
resputil.JSON(w, errors.New("invalid token"))
resputil.JSON(w, errors.New("not authenticated"))
}, nil
}

View File

@@ -20,7 +20,6 @@ func Routes(ctx context.Context) *chi.Mux {
}
func MountRoutes(ctx context.Context, r chi.Router) {
// Only protect application routes with JWT
r.Group(func(r chi.Router) {
r.Use(
auth.DefaultJwtHandler.Verifier(),