dgrijalva / jwt-go

ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:
https://github.com/golang-jwt/jwt
MIT License
10.78k stars 994 forks source link

interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages) #401

Open sarimabbas opened 4 years ago

sarimabbas commented 4 years ago

Thank you for your work on this library. I am currently following this tutorial and running into a strange error: https://echo.labstack.com/cookbook/jwt

The error text is:

echo: http: panic serving [::1]:60942: interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages)

I'm using the v4 preview. I'm able to generate the token fine, but reading it as jwt.Token is giving me the error in the title. The code is:

func restricted(c echo.Context) error {
    user := c.Get("user").(*jwt.Token) // <-- This line 
    claims := user.Claims.(jwt.MapClaims)
    name := claims["name"].(string)
    return c.String(http.StatusOK, "Welcome "+name+"!")
}

The middleware was set as follows:

e.Use(middleware.JWT([]byte("secret")))

Would you have any advice for how to proceed? Thank you

dcormier commented 4 years ago

Since you're referencing the *jwt.Token instance exposed by echo, you would need to use the same version of the package that they are. At least for that type assertion. You can still use the v4 preview in other places, most likely. I'd try something like this:

import (
    ...
    jwtv3 "github.com/dgrijalva/jwt-go"
    "github.com/dgrijalva/jwt-go/v4"
    ...
)

Then, on that type assertion line (and likely the one that's after it), you'd refer to jwtv3 rather than just jwt. Like so:

user := c.Get("user").(*jwtv3.Token)
claims := user.Claims.(jwtv3.MapClaims)
dariov1988 commented 3 years ago

I got the same problem, but for me, the solution does not was the suggested by @dcormier, I double-check that I'm importing github.com/dgrijalva/jwt-go in all parts of my source code but for some reason, after I run go mod tidy in the go.sum file I see that it is trying to use github.com/dgrijalva/jwt-go and github.com/form3tech-oss/jwt-go in my solution I just finishing using github.com/form3tech-oss/jwt-go I can't continue wasting time guessing or doing research about the magic on go mod tidy but if someone in the future read this and knows the exact why of this behavior, please share.