Skip to content
This repository has been archived by the owner on May 24, 2023. It is now read-only.

README: fixing examples in creating token with claims #65

Merged
merged 1 commit into from
Oct 12, 2021

Conversation

dennybiasiolli
Copy link
Contributor

No description provided.

@dennybiasiolli
Copy link
Contributor Author

This will help copy-pasters in creating a new token using provided claims, otherwise the claims variable in the example is never used

@ReneWerner87 ReneWerner87 added the 📒 Documentation Improvements or additions to documentation label Oct 12, 2021
@ReneWerner87 ReneWerner87 merged commit a628715 into gofiber:master Oct 12, 2021
@dennybiasiolli dennybiasiolli deleted the fixing-doc branch October 12, 2021 08:03
@iSLC
Copy link

iSLC commented Oct 12, 2021

Doesn't this break the code tho? because now token is used before it was created.

Ex:

	// Set claims ('token' does not exist here)
	claims := token.Claims.(jwt.MapClaims)
	//...
	// Create token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

@dennybiasiolli
Copy link
Contributor Author

@iSLC you are right, in this case we can use the example from the official documentation: https://pkg.go.dev/github.com/golang-jwt/jwt#example-NewWithClaims-CustomClaimsType

Something like this:

mySigningKey := []byte("AllYourBase")

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.StandardClaims
}

// Create the Claims
claims := MyCustomClaims{
	"bar",
	jwt.StandardClaims{
		ExpiresAt: 15000,
		Issuer:    "test",
	},
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)

@iSLC
Copy link

iSLC commented Oct 12, 2021

@dennybiasiolli yes you are correct. thanks for the prompt reply. I'm a bit new to golang.

For future reference jwt.StandardClaims appears to be deprecated (or to be) and the recommended approach is to use jwt.RegisteredClaims now. And looking at the source I can see why (it uses proper types for standard claims).

Leaving this here for reference:

package main

import (
	"fmt"
	"time"
	"github.com/golang-jwt/jwt/v4"
)

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.RegisteredClaims
}

func main() {
	mySigningKey := []byte("AllYourBase")

	// Create the Claims
	claims := MyCustomClaims{
		"bar",
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 12)),
			Issuer:    "test",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	fmt.Printf("%v %v", ss, err)
}

@dennybiasiolli
Copy link
Contributor Author

thanks @iSLC , let's follow up in #66

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
📒 Documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants