jwt

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2023 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package jwt provides functions for creating and validating JSON Web Tokens (JWT).

It uses the "github.com/golang-jwt/jwt/v4" and "github.com/google/uuid" packages.

The package defines two main types: Claims and Details. Claims is used to represent the JWT claims, and Details represents the token details including the token itself, its payload, and expiration time.

Example Usage:

// Create a new JWT token with the given payload, time-to-live (ttl), and RSA private key.
tokenPayload := map[string]interface{}{"user_id": 123, "role": "admin"}
ttl := time.Hour
privateKey := []byte("YOUR_RSA_PRIVATE_KEY")
tokenDetails, err := jwt.CreateToken(tokenPayload, ttl, privateKey)
if err != nil {
	// Handle error
}

// Validate a JWT token with the given RSA public key.
publicKey := []byte("YOUR_RSA_PUBLIC_KEY")
decodedPayload, err := jwt.ValidateToken(tokenDetails.Token, publicKey)
if err != nil {
	// Handle error
}
fmt.Println("Decoded Payload:", decodedPayload)

Note: The package uses the RS256 signing method for JWTs.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidClaims = errors.New("invalid claims")

ErrInvalidClaims is the error returned when the JWT claims are invalid.

Functions

func ValidateToken

func ValidateToken(token string, key *rsa.PublicKey) (interface{}, error)

ValidateToken validates a JWT token using the given RSA public key. The function parses the token and verifies its signature using the RSA public key. If the token is valid, it returns the payload stored in the token. If the token is invalid, expired, or tampered with, an error is returned.

Types

type Claims

type Claims struct {
	Payload interface{}
	jwt.RegisteredClaims
}

Claims represents the custom JWT claims along with standard registered claims.

type Details

type Details struct {
	ID      uuid.UUID
	Token   string
	Payload interface{}
	Expires time.Time
}

Details represents the JWT token details, including the token itself, its payload, and expiration time.

func CreateToken

func CreateToken(payload interface{}, ttl time.Duration, key *rsa.PrivateKey) (*Details, error)

CreateToken creates a new JWT token with the given payload, time-to-live (ttl), and RSA private key. The function generates a new UUID as the token ID and uses the RS256 signing method for JWTs. The token is signed with the RSA private key, and its expiration time is set according to the ttl value. Returns the token details on success, or an error if any operation fails.

Jump to

Keyboard shortcuts

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