Invalid Json web token in Go
Asked Answered
B

2

5

I am trying to make a Json web token authentication system with Go however I cant seem to get the parsing of the web token working. The error occurs in the following function.

func RequireTokenAuthentication(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
authBackend := InitJWTAuthenticationBackend()

jwtString := req.Header.Get("Authorization")


token, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
        log.Println("Unexpected signing method")
        return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    } else {
        log.Println("The token has been successfully returned")
        return authBackend.PublicKey, nil
    }
})

log.Println(token)
log.Println(token.Valid)

if err == nil && token.Valid && !authBackend.IsInBlacklist(req.Header.Get("Authorization")) {
    next(rw, req)
} else {
    rw.WriteHeader(http.StatusUnauthorized)
    log.P

rintln("Status unauthorized RequireTokenAuthentication")
    }
}

returns the following log

[negroni] Started GET /test/hello
2016/09/13 01:34:46 &{Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe <nil> map[] <nil>  false}
2016/09/13 01:34:46 false
2016/09/13 01:34:46 Status unauthorized RequireTokenAuthentication
[negroni] Completed 401 Unauthorized in 71.628ms

and here is the cURL that I am using to initiate it

curl -H "Authorization: Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe" http://localhost:5000/test/hello

I have also tried curl without Bearer

curl -H "Authorization:eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe" http://localhost:5000/test/hello

The error is occurring because the token is invalid token.Valid = false I have generated it using the following process.

Here is the router

router.HandleFunc("/token-auth", controllers.Login).Methods("POST")

Here is the login controller

    func Login(w http.ResponseWriter, r *http.Request) {
    requestUser := new(models.User)
    decoder := json.NewDecoder(r.Body)
    decoder.Decode(&requestUser)    
    responseStatus, token := utils.Login(requestUser) //here the util file seen below is used
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(responseStatus)
    w.Write(token)

}

This is the util file

    func Login(requestUser *models.User) (int, []byte) {
        authBackend := authentication.InitJWTAuthenticationBackend()

        if authBackend.Authenticate(requestUser) {
            token, err := authBackend.GenerateToken(requestUser.UUID)
            if err != nil {
                return http.StatusInternalServerError, []byte("")
            } else {
                response, _ := json.Marshal(parameters.TokenAuthentication{token})
                return http.StatusOK, response
            }
        }
        return http.StatusUnauthorized, []byte("")
    }

and here is the method used to generate the token

    func (backend *JWTAuthenticationBackend) GenerateToken(userUUID string) (string, error) {
    token := jwt.New(jwt.SigningMethodRS512)

    claims := token.Claims.(jwt.MapClaims)

    claims["exp"] = time.Now().Add(time.Hour * time.Duration(settings.Get().JWTExpirationDelta)).Unix()
    claims["iat"] = time.Now().Unix()
    claims["sub"] = userUUID

    tokenString, err := token.SignedString(backend.privateKey)
    if err != nil {
        panic(err)
        return "", err
    }

    return tokenString, nil
}

How do I fix the Token Parsing system so that the token is valid? If you need any additional information I would be more than happy to make an edit with the respective information. Thank

Bouffe answered 12/9, 2016 at 23:50 Comment(0)
G
7

The error returned by jwt.Parse() says

tokenstring should not contain 'bearer '

So if you remove "Bearer ":

jwtString = strings.Split(jwtString, "Bearer ")[1]

you get a bit further

The token has been successfully returned

however now there's a new error:

key is of invalid type

Sorry it's not a complete answer!

Godliman answered 13/9, 2016 at 0:38 Comment(5)
Is there any more information that I could give to you that would point to the origin of this error?Bouffe
Can you describe how you're creating the key?Godliman
I have added the process I used to generate the token, Thanks!Bouffe
you know what, maybe it does work if you just remove bearer. I can't tell because I don't have the public key from the exampleGodliman
I forgot to mention that I had already tried that, It gives me exactly the same error?Bouffe
M
0

key is of invalid type

type in this context is referring to the dynamic data-type in Go.

For SigningMethodRSA, the public key must be of type *rsa.PublicKey which can be constructed by calling jwt.ParseRSAPublicKeyFromPEM().

The key value returned to the parser might be created with something like:

keyStruct, _ := jwt.ParseRSAPublicKeyFromPEM(myPublicKeyString)

See:

Related:

Mosira answered 29/7, 2019 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.