Golang jwt.StandardClaims time format type issue

5.3k Views Asked by At

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.

5

There are 5 best solutions below

0
Shane umayanga On

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.

0
Jay On

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)},
}
0
Daivs On
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

0
Lamech Desai On

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"
1
CONG NGUYEN On

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))