jwt

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package jwt generates and validates JSON Web Tokens.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEmptySecret = errors.New("jwt: empty secret")

ErrEmptySecret is returned when a token is generated or validated with an empty secret, which would make every token forgeable.

Functions

func GenerateToken

func GenerateToken(claims MapClaims, secret string) (string, error)

GenerateToken generates a new JWT token. The token carries no "exp" claim unless claims already has one; prefer GenerateTokenWithExpiry.

Example

Sign a token, validate it with the same secret, then read a claim back out.

package main

import (
	"fmt"

	"github.com/rahmadafandi/fibr/jwt"
)

func main() {
	secret := "super-secret-key"

	token, err := jwt.GenerateToken(jwt.MapClaims{"sub": "user-42", "role": "admin"}, secret)
	if err != nil {
		panic(err)
	}

	parsed, err := jwt.ValidateToken(token, secret)
	if err != nil {
		panic(err)
	}

	claims, err := jwt.ExtractClaimsFromJwt(parsed)
	if err != nil {
		panic(err)
	}

	fmt.Println("sub:", claims["sub"])
	fmt.Println("role:", claims["role"])
}
Output:
sub: user-42
role: admin

func GenerateTokenWithExpiry

func GenerateTokenWithExpiry(claims MapClaims, secret string, ttl time.Duration) (string, error)

GenerateTokenWithExpiry generates a new JWT token that expires after ttl. It writes the "exp" claim into the provided claims map, overwriting any existing "exp" value.

Types

type MapClaims

type MapClaims = jwt.MapClaims

MapClaims is re-exported from golang-jwt so callers need not import that package directly.

func Claims

func Claims(c *fiber.Ctx, localKey string, claims ...MapClaims) (MapClaims, error)

Claims gets claims from a JWT token in the fiber context or set claims to the fiber context.

func ExtractClaimsFromJwt

func ExtractClaimsFromJwt(jwtToken *Token) (MapClaims, error)

ExtractClaimsFromJwt extracts the MapClaims from a parsed JWT token. It returns an error if the token's Claims field is not a MapClaims value.

type Token

type Token = jwt.Token

Token is re-exported from golang-jwt so callers need not import that package directly.

func ValidateToken

func ValidateToken(tokenString string, secret string) (*Token, error)

ValidateToken validates a JWT token.

Example (WrongSecret)

Validating with the wrong secret fails.

package main

import (
	"fmt"

	"github.com/rahmadafandi/fibr/jwt"
)

func main() {
	token, _ := jwt.GenerateToken(jwt.MapClaims{"sub": "user-42"}, "right-secret")

	_, err := jwt.ValidateToken(token, "wrong-secret")
	fmt.Println("valid:", err == nil)
}
Output:
valid: false

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL