go-chi / jwtauth

JWT authentication middleware for Go HTTP services
MIT License
541 stars 91 forks source link

Problem with the Verifier #43

Closed alexandrubese closed 4 years ago

alexandrubese commented 4 years ago
package routes

import (
    "alexapp.pck.com/handler"
    "fmt"
    "github.com/go-chi/chi"
    "github.com/go-chi/jwtauth"
    "net/http"
)
var tokenAuth *jwtauth.JWTAuth

//InitIndexRoutes function
func InitRestrictedRoutes(c *chi.Mux, h *handler.Handler) {
    // Protected routes
    c.Group(func(r chi.Router) {

        // Seek, verify and validate JWT tokens
        r.Use(jwtauth.Verifier(tokenAuth))

        // Handle valid / invalid tokens. In this example, we use
        // the provided authenticator middleware, but you can write your
        // own very easily, look at the Authenticator method in jwtauth.go
        // and tweak it, its not scary.
        r.Use(jwtauth.Authenticator)

        r.Get("/restricted", func(w http.ResponseWriter, r *http.Request) {
            _, claims, _ := jwtauth.FromContext(r.Context())

            w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
        })
    })
}
Screenshot 2019-09-10 at 21 52 54

It seems that for a reason the var tokenAuth *jwtauth.JWTAuth is of value nil in the actual jwtauth.Verifier(tokenAuth) code. So this gives me the error :

2019/09/10 21:39:07 http: panic serving [::1]:53185: runtime error: invalid memory address or nil pointer dereference
goroutine 103 [running]:
net/http.(*conn).serve.func1(0xc00029c320)
        /usr/local/go/src/net/http/server.go:1769 +0x139
panic(0x1392660, 0x16ea470)
        /usr/local/go/src/runtime/panic.go:522 +0x1b5
github.com/go-chi/jwtauth.(*JWTAuth).Decode(0x0, 0xc0001cc547, 0x65, 0x10, 0x10, 0xc00005ba88)
       /src/github.com/go-chi/jwtauth/jwtauth.go:143 +0x26
github.com/go-chi/jwtauth.VerifyRequest(0x0, 0xc000169000, 0xc000246660, 0x3, 0x3, 0x0, 0xc0001e5f20, 0x0)
        /src/github.com/go-chi/jwtauth/jwtauth.go:106 +0x94
github.com/go-chi/jwtauth.Verify.func1.1(0x1483080, 0xc00025cfc0, 0xc000169000)
        /src/github.com/go-chi/jwtauth/jwtauth.go:80 +0x98

In the actual example, you have: var tokenAuth *jwtauth.JWTAuth

//And you assign a value to it in the init() function : // tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)

In my case, I already have the token generated and saved somewhere else and all I want to do is use that token.

So when the code arrives in my initRestrictedFunction , what should the value for : tokenAuth be ? On the line: r.Use(jwtauth.Verifier(tokenAuth))

Thanks

alexandrubese commented 4 years ago

Ah sorry, I missed the line:

tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)

Once I added this - it all worked. I am going to close this issue