golang-jwt / jwt

Go implementation of JSON Web Tokens (JWT).

Home Page:https://golang-jwt.github.io/jwt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Key can be anything, even empty

Edmartt opened this issue · comments

jwt/token.go

Line 71 in 0d2f0d4

sig, err := t.Method.Sign(sstr, key)

I think this line needs to be validated because I was making a mistake here, forgot to set env var and even like that the key string travels empty and it's assigned. I'm not sure if this is just my fault and a trivial thing but if not, It's a thing to be careful about.

i.e if you turn the secret key into bytes(array) the array will be empty

For refererences, look at this:

https://github.com/Edmartt/go-authentication-api/blob/745596863a538ffcbbc718c6519bff0dabd1d4e8/pkg/jwt/jwt.go#L19

I realized that even when SignedString method has interface as param, if you don't send a bytes array, the returned value is an empty string

imagen

this is the response in this case:

imagen

And now look at this:

imagen

This is the response in this case:

imagen

If the type is an interface I can send a string without any problem, but that is the response when I'm not sending the data as bytes

Hi @Edmartt

There are two issues here

  1. Regarding your first post: yes, we do not really check whether you pass an empty array as a key. This is somewhat in the responsibility of the caller. Because of course we could check if it is empty, but then we could argue that a key of size 1 is also not suitable, etc.

  2. Yes, because of the way the API works (it was built back when we did not have generics in Go), the key can be any or interface{}. So yes you can pass in a string. BUT, you will get an error "key is of invalid type" (ErrInvalidKeyType) and the token will be empty. So in your second example, yes the token is empty, but you also ignored the error value.

I think this is working as intended, so closing the issue. But feel free to continue the discussion.

Agree with the points Christian mentioned above, although checking for the error won't help here since token.SignedString([]byte("")) is valid, unfortunately. So ensuring you have a valid key non-empty is very important.


Side note, it's a Go best practice to check for errors and avoid using return values if err != nil, so this bit:

func X() (tokenString string, err error) { 
  tokenString, tokenError := token.SignedString(secretKeyBytes)
  if tokenError != nil{
    return
  }
}

should really be returning an error instead of a named return (which will be nil). E.g.,

func X() (string, error) { 
  tokenString, err := token.SignedString(secretKeyBytes)
  if err != nil{
    // let the caller gracefully handle the error
    // https://go.dev/doc/effective_go#errors
    return "", err
  }
  // use return value only once we checked for an error
  return tokenString, nil
}