travelgateX / go-jwt-tools

Golang authorization middleware for JWT tokens. JWT tools
http://www.travelgatex.com
GNU General Public License v3.0
9 stars 9 forks source link

Return 401 for a invalid bearer #21

Closed alexjmoya closed 5 years ago

guzmanthegood commented 5 years ago

Hi @alexjmoya , for why reason in this case you returned a formatted error and in the previous error check you print the error? its not possible to apply the same in both cases?

In truth, I don't know the implications, if you can explain it to me better, thank you.

func Middleware(p Parser) func(h http.Handler) http.Handler {
    return func(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            authHeader := r.Header.Get("Authorization")
            if authHeader == "" {
                fmt.Fprintln(w, "Authorization header required")  <<<<<<<<<<
                return
            }

            pt, err := p.Parse(authHeader)
            if err != nil {
                http.Error(w, err.Error(), http.StatusUnauthorized) <<<<<<<<<<<<
                return
            }

            ctx := context.WithValue(r.Context(), activeUser, pt)
            h.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}
alexjmoya commented 5 years ago

Hi @alexjmoya , for why reason in this case you returned a formatted error and in the previous error check you print the error? its not possible to apply the same in both cases?

In truth, I don't know the implications, if you can explain it to me better, thank you.

func Middleware(p Parser) func(h http.Handler) http.Handler {
  return func(h http.Handler) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          authHeader := r.Header.Get("Authorization")
          if authHeader == "" {
              fmt.Fprintln(w, "Authorization header required")  <<<<<<<<<<
              return
          }

          pt, err := p.Parse(authHeader)
          if err != nil {
              http.Error(w, err.Error(), http.StatusUnauthorized) <<<<<<<<<<<<
              return
          }

          ctx := context.WithValue(r.Context(), activeUser, pt)
          h.ServeHTTP(w, r.WithContext(ctx))
      })
  }
}

Hi @guzmanweb , The goal, in this case, is to return a http.StatusUnauthorized when the authHeader is wrong. You have all rigth we must return the same status in both cases... let me correct the code. Apologise for the confusion

guzmanthegood commented 5 years ago

perfect!