Skip to content

Commit

Permalink
fix(middleware): return JSON error
Browse files Browse the repository at this point in the history
  • Loading branch information
ncarlier committed Feb 23, 2021
1 parent 4a175bb commit bda0f2f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
24 changes: 24 additions & 0 deletions pkg/middleware/json-errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package middleware

import (
"encoding/json"
"net/http"
)

type errorObject struct {
Message string `json:"message"`
}

type errorsObject struct {
Errors []errorObject `json:"errors"`
}

func jsonErrors(w http.ResponseWriter, message string, code int) {
err := errorsObject{
Errors: []errorObject{{Message: message}},
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
json.NewEncoder(w).Encode(err)
}
8 changes: 4 additions & 4 deletions pkg/middleware/oidc-jwt-auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func OpenIDConnectJWTAuth(authority string) Middleware {
return nil, errors.New("kid header not found in token")
})
if err != nil {
http.Error(w, err.Error(), 401)
jsonErrors(w, err.Error(), 401)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
Expand All @@ -44,12 +44,12 @@ func OpenIDConnectJWTAuth(authority string) Middleware {
username = val.(string)
}
if username == "" {
http.Error(w, "No username inside token", 403)
jsonErrors(w, "No username inside token", 403)
return
}
user, err := service.Lookup().GetOrRegisterUser(ctx, username)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
jsonErrors(w, err.Error(), http.StatusInternalServerError)
return
}
isAdmin := false
Expand All @@ -68,7 +68,7 @@ func OpenIDConnectJWTAuth(authority string) Middleware {
inner.ServeHTTP(w, r.WithContext(ctx))
return
}
http.Error(w, "Unauthorized", 401)
jsonErrors(w, "Unauthorized", 401)
})
}
}
3 changes: 1 addition & 2 deletions pkg/middleware/proxy-auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ func ProxyAuth(inner http.Handler) http.Handler {
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="Ah ah ah, you didn't say the magic word"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorized\n"))
jsonErrors(w, "Unauthorized", 401)
})
}

0 comments on commit bda0f2f

Please sign in to comment.