3

I am using this package github.com/dgrijalva/jwt-go/v4 to set up claims in a Login function:

now := time.Now()
claims := &jwt.StandardClaims{
    Issuer: "Test",
    ExpiresAt: now.Add(time.Hour * 24).Unix(),
}

The IDE keeps telling me:

Cannot use 'now.Add(time.Hour * 24).Unix()' (type int64) as the type Time.

I read that as I have the wrong typed value, however, on all the examples I've seen online, this is exactly how the majority set up this up.

I am still learning go and so I am not sure the proper way to convert this time format into something that is valid.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
porterhaus
  • 439
  • 2
  • 5
  • 17

5 Answers5

3

In github.com/golang-jwt/jwt/v4 StandardClaims type is deprecated, you should replace StandardClaims with RegisteredClaims.

And about Cannot use 'now.Add(time.Hour * 24).Unix()' (type int64) as the type Time. you need to use NumericDate type, so your code will looks like this:

claims := &jwt.RegisteredClaims{
    Issuer: "Test",
    ExpiresAt: &jwt.NumericDate{now.Add(time.Hour * 24)},
}
Jay
  • 31
  • 1
  • 3
2

Okay, you can change

github.com/dgrijalva/jwt-go/v4 => github.com/golang-jwt/jwt/v4   //v4.4.3

StandardClaims => RegisteredClaims

now.Add(time.Hour * 24).Unix()  => jwt.NewNumericDate(now.Add(time.Hour * 24))
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 22 '22 at 14:11
1

ExpiresAt requires the datatype to be *time.Time and the function Unix() returns the time in a number of seconds in int64.

I recommend you to use the package github.com/golang-jwt/jwt rather than the one you are using now, which is no longer maintained.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
0
func GenerateToken(username, password string) (string, error) {
    nowTime := time.Now()
    expireTime := nowTime.Add(12 * time.Hour)

    claims := Claims{
        username,
        password,
        jwt.RegisteredClaims{
            ExpiresAt: jwt.NewNumericDate(expireTime),
            Issuer:    "test",
        },
    }
    
    tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    token, err := tokenClaims.SignedString(jwtSecret)

    return token, err
}

You can try it

Daivs
  • 1
  • 1
0

your code is Okay the problem is with the importation of your package you can change the import

from

"github.com/dgrijalva/jwt-go/v4"

to

"github.com/dgrijalva/jwt-go"
Lamech Desai
  • 709
  • 6
  • 11