A simple, secure, and easy-to-use Golang library for generating and validating JWT tokens with custom claims, full test coverage, and mock support.
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.
# Add the library as a dependency
go get github.com/not-empty/jwt-manager-go-lib
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)
}
See ./example/jwt_example.go
for a full runnable demonstration of all public methods.
- Unit & feature tests: run the script:
./test.sh
- Coverage report: open the generated HTML:
open ./test/coverage-unit.html
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.
This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.
Contribuite by submitting issues and pull requests. Feedback and improvements are always welcome.
Not Empty Foundation - Free codes, full minds