golang-jwt / jwt

Go implementation of JSON Web Tokens (JWT).
https://golang-jwt.github.io/jwt/
MIT License
6.98k stars 335 forks source link

I have no RegisteredClaims. I have error key is invalid #381

Closed udonetsm closed 6 months ago

udonetsm commented 6 months ago

I'm trying to get access token with custom claims. But i get error(key s invalid) from SignedString function always. I can't follow exmple because the package doesn't contain RegisteregClaims type, only StandardClaims. Where am i wrong.

           package controllers

            import (
                "encoding/json"
                "net/http"
                "time"

                "github.com/golang-jwt/jwt"
            )

            type repl struct {
                Info  any `json:"inf,omitempty"`
                Error any `json:"err,omitempty"`
            }

            const ISSUER = "/authorization/server" //should be change to the real url/uri

            type CustomClaims struct {
                UAgent string
                jwt.StandardClaims
            }

            func TokenAccess(w http.ResponseWriter, r *http.Request) {
                encoder := json.NewEncoder(w)
                claims, secret := generateClaims(r)
                signed, err := generateAccess(secret, claims)
                if err != nil {
                    w.WriteHeader(http.StatusBadRequest)
                    encoder.Encode(&repl{Error: err.Error()})
                    return
                }
                encoder.Encode(&repl{Info: signed})
            }

            func generateAccess(secret string, claims *CustomClaims) (string, error) {
                token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
                return token.SignedString([]byte(secret))
            }

            func generateClaims(r *http.Request) (*CustomClaims, string) {
                r.ParseForm()
                return &CustomClaims{
                    r.UserAgent(),
                    jwt.StandardClaims{
                        Id:        r.FormValue("uid"),
                        Issuer:    ISSUER,
                        IssuedAt:  time.Now().UnixNano(),
                        ExpiresAt: time.Now().Add(time.Hour).UnixNano(),
                    },
                }, r.FormValue("secret")
            }
udonetsm commented 6 months ago

I found mistake. Should use []byte(secret) in SignedString. But it doesn't work yet.

udonetsm commented 6 months ago

SignedString function with []byte(secret) doesn't work yet

udonetsm commented 6 months ago

It works only with HS256 key. Cloase this issue

udonetsm commented 6 months ago

Works with HS256 only