Add a specific return type / type constraint to `Keyfunc` and `SignedString`
oxisto opened this issue · comments
Christian Banse commented
Currently, Keyfunc
expects to return an interface{}
and SignedString
expects a interface{}
parameter. This often lead to confusing, what exactly these functions expect. We should therefore constrain the types of these functions. A possible solution could look like this:
diff --git a/token.go b/token.go
index c8ad7c7..644b15e 100644
--- a/token.go
+++ b/token.go
@@ -1,15 +1,24 @@
package jwt
import (
+ "crypto"
"encoding/base64"
"encoding/json"
)
+type ParsingKey interface {
+ crypto.PublicKey | []uint8 | unsafeNoneMagicConstant
+}
+
+type SigningKey interface {
+ crypto.PrivateKey | []uint8 | unsafeNoneMagicConstant
+}
+
// Keyfunc will be used by the Parse methods as a callback function to supply
// the key for verification. The function receives the parsed, but unverified
// Token. This allows you to use properties in the Header of the token (such as
// `kid`) to identify which key to use.
-type Keyfunc func(*Token) (interface{}, error)
+type Keyfunc func(*Token) (ParsingKey, error)
// Token represents a JWT Token. Different fields will be used depending on
// whether you're creating or parsing/verifying a token.
@@ -46,7 +55,7 @@ func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *To
// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types
// for an overview of the different signing methods and their respective key
// types.
-func (t *Token) SignedString(key interface{}) (string, error) {
+func (t *Token) SignedString(key SigningKey) (string, error) {
sstr, err := t.SigningString()
if err != nil {
return "", err