Reputation: 7867
I am starting with go and jwt.
For testing purpose I have a hardcoded secret. And a route to get the key
const secretKey = "YOLOSWAG"
var mySigningKey = []byte(secretKey)
var GetTokenHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = jwt.MapClaims{
"admin": true,
"name": "John Doe",
"exp": time.Now().Add(time.Hour * 24).Unix(),
}
tokenString, _ := token.SignedString(mySigningKey)
w.Write([]byte(tokenString))
})
var jwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return mySigningKey, nil
},
SigningMethod: jwt.SigningMethodHS256,
})
and later added the jwtMiddleware to my route
r.Handle("/protected", jwtMiddleware.Handler(ProtectedTestHandler)).Methods("GET")
So localhost:3000/protected will output an error Required authorization token not found
this works.
/token will output my token. This works too.
And finally /protected with (in postman) Authorization: Bearer {token}
Will output illegal base64 data at input byte 0 I am really confused why this happens.
Upvotes: 8
Views: 10640
Reputation: 416
I'm an absolute newb with GO at the moment as I'm learning this right now but I ran into this same issue and realized that the code I was using to pull the JWT Token out of the Authorization header was leaving a blank space as the first character of the JWT token string. This was presumably causing the string not be base64 decoded.
This was the offending code which was leaving a blank space in front of the. JWT token:
This removed the first 6 chars instead of 5 from the Authorization header to correct the problem.
I ran into this problem when following the tutorial here: https://medium.com/wesionary-team/jwt-authentication-in-golang-with-gin-63dbc0816d55 Repo: https://github.com/Bikash888/jwt-auth
Upvotes: 4
Reputation: 3578
Don't use curlies around your token. The documentation in many places is confusing because it wraps your token in curlies. It's meant to represent a placeholder. You're not actually supposed to wrap your token with them. Do NOT do it like this.
Bearer {my-special-token}
It should be done like this
Bearer my-special-token
Upvotes: 3