Reputation: 491
Got JWT is invalid
with new version of "github.com/auth0/go-jwt-middleware/v2"
successfully generate token with "github.com/golang-jwt/jwt/v4"
plugin, and try to use it on request but rejected on middleware, i guess the issues in go-jwt-middleware
. there is some missing with implementation, maybe anyone has already implement and want to share please
Here is the code:
type Claims struct {
Username string `json:"username"`
Role string `json:"role"`
Id string `json:"id"`
Avatar string `json:"avatar"`
jwt.StandardClaims
}
func (c *Claims) Validate(ctx context.Context) error {
return nil
}
var jwtKey = []byte("secret")
func Middleware(h http.Handler) http.Handler {
keyFunc := func(ctx context.Context) (interface{}, error) {
return jwtKey, nil
}
customClaims := func() validator.CustomClaims {
return &Claims{}
}
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer",
[]string{"audience"},
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
if err != nil {
log.Fatalf("Failed to set up the validator: %v", err)
}
// Set up the middleware.
middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, token, err := ParseToken(r)
if !token.Valid || err != nil {
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
return
}
h.ServeHTTP(w, r)
}))
}
func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
expirationTime := time.Now().Add(time.Hour * 24).Unix()
claims := &Claims{
Id: id,
Username: username,
Role: role,
Avatar: avatar,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", 0, err
}
return tokenString, expirationTime, nil
}
And i don't found any doccumentation for the value for issuer
&& audience
option on validator. just follow the example:
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer", <------------ issuer
[]string{"audience"}, <------------ audience
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
Upvotes: 1
Views: 1470
Reputation: 2398
Issuer: issuerURL,
Audience: audience,
The audience value is a string -- typically, the base address of the resource being accessed. for example which services, APIs, products should accept this token as an access token for the service. A token valid for Stackoveflow should not be accepted for the Stack exchange website, even if both of them have the same issuer, they’ll have different audiences.
Issuer value is a string like this https://<issuer-url>/
Who created the token. like token issued by GitHub or LinkedIn and this can be verified by using the OpenID configuration endpoint
Upvotes: 1