auth0 / go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
MIT License
1.08k stars 205 forks source link

An error occured while validating JWT: jwt invalid: error getting the keys from the key func: could not get well known endpoints from url https:///.well-known/openid-configuration: Get "https:///.well-known/openid-configuration": http: no Host in request URL #187

Closed Jomy10 closed 1 year ago

Jomy10 commented 1 year ago

Checklist

Description

I get the error An error occured while validating JWT: jwt invalid: error getting the keys from the key func: could not get well known endpoints from url https:///.well-known/openid-configuration: Get "https:///.well-known/openid-configuration": http: no Host in request URL when trying to use the JWT middleware.

Reproduction

I have the following middleware:

package middleware

import (
        "os"
        "time"
        "log"
        "fmt"
        "context"

        "net/http"
        "net/url"

        "github.com/auth0/go-jwt-middleware/v2"
        "github.com/auth0/go-jwt-middleware/v2/jwks"
        "github.com/auth0/go-jwt-middleware/v2/validator"
)

type CustomClaims struct {
        Scope string `json:"scope"`
}

func (c CustomClaims) Validate(ctx context.Context) error {
        return nil
}

// Only handles request when the user is authorized to access the endpoint
func EnsureValidToken() func(next http.Handler) http.Handler {
        issuerURL, err := url.Parse("https://" + os.Getenv("EMAIL_API_AUTH0_DOMAIN") + "/")
        if err != nil {
                panic(fmt.Sprintf("Failed to parse the issuer url: %v", err))
        }

        provider := jwks.NewCachingProvider(issuerURL, 5 * time.Minute)

        jwtValidator, err := validator.New(
                provider.KeyFunc,
                validator.RS256,
                issuerURL.String(),
                []string{"https://ksa-email-api.jomy.dev"}, // AUTH0 API Identifier (Audience)
                validator.WithCustomClaims(
                        func() validator.CustomClaims {
                                return &CustomClaims{}
                        },
                ),
                validator.WithAllowedClockSkew(time.Minute),
        )
        if err != nil {
                panic(err)
        }

        errorHandler := func(resp http.ResponseWriter, req *http.Request, err error) {
                log.Printf("An error occured while validating JWT: %v", err)
                log.Println(req)

                resp.Header().Set("Content-Type", "application/json")
                resp.WriteHeader(http.StatusUnauthorized)
                resp.Write([]byte(`{"message":"Failed to validate JWT."}`))
        }

        middleware := jwtmiddleware.New(
                jwtValidator.ValidateToken,
                jwtmiddleware.WithErrorHandler(errorHandler),
        )

        // return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
        //      next.ServeHTTP(resp, req)
        // })
        return func(next http.Handler) http.Handler {
                return middleware.CheckJWT(next)
        }
}

I generate a JWK token:

curl --request POST \
  --url 'https://dev-tce1ggxc6lqxphjc.eu.auth0.com/oauth/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type=client_credentials \
  --data client_id=MY_CLENT_ID \
  --data client_secret=MY_CLIENT_SECRET \
  --data audience=https://ksa-email-api.jomy.dev

I then use it in a request that uses this middleware:

curl \
  --request POST \
  --url https://ksa-email-api.jomy.dev/the_endpoint \
  --header "Authorization: Bearer THE_GENERATED_TOKEN" \
  --header 'content-type: application/json' \
  --data '...'

This gives me as response: {"message":"Failed to validate JWT."}, while on the server I get AAn error occured while validating JWT: jwt invalid: error getting the keys from the key func: could not get well known endpoints from url https:///.well-known/openid-configuration: Get "https:///.well-known/openid-configuration": http: no Host in request URL.

Go JWT Middleware version

v2.0.0

Go version

1.19.4 linux/amd64

ewanharris commented 1 year ago

Hey @Jomy10, apologies for our delay in getting back to you here. Running your provided code I only get the error you mentioned when the EMAIL_API_AUTH0_DOMAIN environment variable is not provided. Can you confirm that this is present wherever you are running your code?

Jomy10 commented 1 year ago

Hi, I ended up using something else for this project, but I do remember checking if the environment variable was present by printing it out, which worked

ewanharris commented 1 year ago

It's curious that it printed out just fine, but didn't construct the URL correctly.

Given that I can't reproduce this and it seems the issue lies more in configuration as the URL was constructed before being passed to jwks.NewCachingProvider I'm going to close this issue out. Thank you for filing this issue.