Skip to content

JWT Manager Golang Library: A simple, secure, and easy-to-use Golang library for generating and validating JWT tokens with custom claims, full test coverage, and mock support.

Notifications You must be signed in to change notification settings

not-empty/jwt-manager-go-lib

Repository files navigation

JWT Manager Golang Library

A simple, secure, and easy-to-use Golang library for generating and validating JWT tokens with custom claims, full test coverage, and mock support.


Description

This library provides:

  • JWT generation using HMAC-SHA256, with customizable expiration and refresh thresholds.
  • Methods to validate signature, check expiration (IsOnTime), determine if a token needs refresh (TokenNeedsRefresh), and decode payload.
  • 100% unit and feature tests.
  • A mock implementation (mock/JwtManagerMock) to simplify testing your own code.

Installation

# Add the library as a dependency
go get github.com/not-empty/jwt-manager-go-lib

Usage

Import the package and initialize the manager:

import (
  "fmt"
  "log"

  "github.com/not-empty/jwt-manager-go-lib/jwt_manager"
)

func main() {
  // secret, issuer, expire (sec), renew threshold (sec)
  mgr := jwt_manager.NewJwtManager("my-secret-key", "my-app", 3600, 1800)

  // generate token with custom claims
  custom := map[string]interface{}{"role": "admin", "org": "example"}
  token := mgr.Generate("audience123", "subject123", custom)
  fmt.Println("Token:", token)

  // validate signature
  ok, err := mgr.IsValid(token)
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println("Valid signature?", ok)

  // check expiration
  onTime, _ := mgr.IsOnTime(token)
  fmt.Println("On time?", onTime)

  // check refresh threshold
  needs, _ := mgr.TokenNeedsRefresh(token)
  fmt.Println("Needs refresh?", needs)

  // decode payload
  payload, _ := mgr.DecodePayload(token)
  fmt.Printf("Payload: %+v\n", payload)
}

Example

See ./example/jwt_example.go for a full runnable demonstration of all public methods.

Running Tests

  • Unit & feature tests: run the script:
    ./test.sh
  • Coverage report: open the generated HTML:
    open ./test/coverage-unit.html

Mocking

A mock implementation is provided in mock/JwtManagerMock. To see it in action, run:

./mock.sh

Use mock.JwtManagerMock in your tests to override any behavior of the JWT manager. See ./mock/jwt_manager_mock_test.go for usage examples.

License

This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.

Contributing

Contribuite by submitting issues and pull requests. Feedback and improvements are always welcome.


Not Empty Foundation - Free codes, full minds

About

JWT Manager Golang Library: A simple, secure, and easy-to-use Golang library for generating and validating JWT tokens with custom claims, full test coverage, and mock support.

Resources

Stars

Watchers

Forks

Packages

No packages published