The easiest JWT library to GO

JWT Go

Build Status Go Report Card GoDoc

The easiest JWT Library that could be a starting point for your project.

Installation

go get github.com/supanadit/jwt-go

Quick Start

package main

import (
	"fmt"
	"github.com/supanadit/jwt-go"
	"log"
)

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

	// Create default authorization
	auth := jwt.Authorization{
		Username: "admin",
		Password: "admin",
	}

	// Generate JWT Token from default authorization model
	token, err := auth.GenerateJWT()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("JWT Token : " + token)

	// Verify the token
	valid, err := auth.VerifyJWT(token)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Print("Status : ")

	if valid {
		fmt.Println("Valid")
	} else {
		fmt.Println("Invalid")
	}
}
Custom Authorization

package main

import (
	"fmt"
	"github.com/supanadit/jwt-go"
	"log"
)

type Login struct {
	Email    string
	Password string
	Name     string
}

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

	// Create default authorization
	auth := Login{
		Email:    "[email protected]",
		Password: "asd",
		Name:     "asd",
	}

	// Generate JWT Token from default authorization model
	token, err := jwt.GenerateJWT(auth)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("JWT Token : " + token)

	// Variable for decoded JWT token
	var dataAuth Login
	// Verify the token
	valid, err := jwt.VerifyAndBindingJWT(&dataAuth, token)
	if err != nil {
		fmt.Println(err)
	}

	// or simply you can do this, if you don't need to decode the JWT
	// valid, err := jwt.VerifyJWT(token)
	// if err != nil {
	//	 fmt.Println(err)
	// }

	fmt.Print("Status : ")

	if valid {
		fmt.Println("Valid")
	} else {
		fmt.Println("Invalid")
	}
}

Encrypt & Verify Password

package main

import (
	"fmt"
	"github.com/supanadit/jwt-go"
	"log"
)

type Login struct {
	Email    string
	Password string
}

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

	// Create authorization from your own struct
	auth := Login{
		Email:    "[email protected]",
		Password: "123",
	}

	// Encrypt password, which you can save to database
	ep, err := jwt.EncryptPassword(auth.Password)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Encrypted Password " + string(ep))

	// Verify Encrypted Password
	valid, err := jwt.VerifyPassword(string(ep), auth.Password)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Print("Status : ")

	if valid {
		fmt.Println("Valid")
	} else {
		fmt.Println("Invalid")
	}
}

Decrypt Password

No you can't, as the thread at Stack Exchange

bcrypt is not an encryption function, it's a password hashing function, relying on Blowfish's key scheduling, not its encryption. Hashing are mathematical one-way functions, meaning there is no way to reverse the output string to get the input string.
of course only Siths deal in absolutes and there are a few attacks against hashes. But none of them are "reversing" the hashing, AFAIK.

so that enough to secure the password

Set Expired Time

package main

import (
	"fmt"
	"github.com/supanadit/jwt-go"
	"log"
)

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")
 
    // You can simply do this, jwt.setExpiredTime(Hour,Minute,Second)
	jwt.SetExpiredTime(0, 0, 1)
}

Support Gin Web Framework

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/supanadit/jwt-go"
	"net/http"
)

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

	// Create authorization
	auth := jwt.Authorization{
		Username: "admin",
		Password: "123",
	}

	router := gin.Default()

	// Login / Authorization for create JWT Token
	router.POST("/auth", func(c *gin.Context) {
		var a jwt.Authorization
		err := c.Bind(&a)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"status": "Invalid body request",
				"token":  nil,
			})
		} else {
			valid, err := auth.VerifyPassword(a.Password)
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"status": "Wrong username or password",
					"token":  nil,
				})
			} else {
				if valid {
					token, err := a.GenerateJWT()
					if err != nil {
						c.JSON(http.StatusInternalServerError, gin.H{
							"status": "Can't generate JWT token",
							"token":  nil,
						})
					} else {
						c.JSON(http.StatusOK, gin.H{
							"status": "Success",
							"token":  token,
						})
					}
				} else {
					c.JSON(http.StatusBadRequest, gin.H{
						"status": "Wrong username or password",
						"token":  nil,
					})
				}
			}
		}
	})

	// Test Authorization
	router.GET("/test", func(c *gin.Context) {
		// Variable for binding if you need decoded JWT
		var dataAuth jwt.Authorization
		// Verify and binding JWT
		token, valid, err := jwt.VerifyAndBindingGinHeader(&dataAuth, c)

		// in case if you don't want to decode the JWT, simply use this code
		// token, valid, err := jwt.VerifyGinHeader(c)

		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": err.Error(),
			})
		} else {
			if valid {
				c.JSON(http.StatusOK, gin.H{
					"status": token + " is valid",
				})
			} else {
				c.JSON(http.StatusBadRequest, gin.H{
					"status": "Invalid",
				})
			}
		}
	})

	_ = router.Run(":8080")
}

Support Echo Web Framework

package main

import (
	"github.com/labstack/echo/v4"
	"github.com/supanadit/jwt-go"
	"net/http"
)

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

	// Create authorization
	auth := jwt.Authorization{
		Username: "admin",
		Password: "123",
	}

	e := echo.New()

	// Login / Authorization for create JWT Token
	e.POST("/auth", func(c echo.Context) error {
		a := new(jwt.Authorization)
		// Create struct for response, or you can create globally by your self
		var r struct {
			Status string
			Token  string
		}
		err := c.Bind(a)
		if err != nil {
			r.Status = "Invalid body request"
			return c.JSON(http.StatusBadRequest, &r)
		} else {
			valid, err := auth.VerifyPassword(a.Password)
			if err != nil {
				r.Status = "Wrong username or password"
				return c.JSON(http.StatusBadRequest, &r)
			} else {
				if valid {
					token, err := a.GenerateJWT()
					if err != nil {
						r.Status = "Can't generate JWT Token"
						return c.JSON(http.StatusInternalServerError, &r)
					} else {
						r.Status = "Success"
						r.Token = token
						return c.JSON(http.StatusOK, &r)
					}
				} else {
					r.Status = "Wrong username or password"
					return c.JSON(http.StatusBadRequest, &r)
				}
			}
		}
	})

	// Test Authorization
	e.GET("/test", func(c echo.Context) error {
		// Create struct for response
		var r struct {
			Status string
		}
		// Variable for binding if you need decoded JWT
		dataAuth := new(jwt.Authorization)
		// Verify and binding JWT
		token, valid, err := jwt.VerifyAndBindingEchoHeader(&dataAuth, c)

		// in case if you don't want to decode the JWT, simply use this code
		// Token, valid, err := jwt.VerifyEchoHeader(c)

		if err != nil {
			r.Status = err.Error()
			return c.JSON(http.StatusBadRequest, &r)
		} else {
			if valid {
				r.Status = token + " is valid"
				return c.JSON(http.StatusOK, &r)
			} else {
				r.Status = "Invalid"
				return c.JSON(http.StatusBadRequest, &r)
			}
		}
	})

	// Start server
	e.Logger.Fatal(e.Start(":1323"))
}

Disable & Enable Authorization

package main

import (
	"github.com/supanadit/jwt-go"
)

func main() {
	// Set Your JWT Secret Code, its optional but important, because default secret code is not secure
	jwt.SetJWTSecretCode("Your Secret Code")

    // Disable authorization, meaning when verify jwt token it will return true even if the token was expired or invalid
	jwt.DisableAuthorization()

	// or

    // Enable authorization
	jwt.EnableAuthorization()
}

Set HMAC Signing Method

package main

import "github.com/supanadit/jwt-go"

func main() {
	// Set HMAC signing method
	jwt.SetHMACSigningMethod(jwt.HS256()) // or jwt.HS384(), jwt.HS512()
}

Thanks to

Owner
Supan Adit Pratama
Software Engineer
Supan Adit Pratama
Similar Resources

simple-jwt-provider - Simple and lightweight provider which exhibits JWTs, supports login, password-reset (via mail) and user management.

Simple and lightweight JWT-Provider written in go (golang). It exhibits JWT for the in postgres persisted user, which can be managed via api. Also, a password-reset flow via mail verification is available. User specific custom-claims also available for jwt-generation and mail rendering.

Dec 18, 2022

YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等

YSHOP-GO 后台管理系统 项目简介 YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等 体验地址: https://go

Dec 30, 2022

Small Lambda function which performs a Aws:Sts:AssumeRole based on the presented JWT-Token

About This implements a AWS Lambda handler which takes a JWT-Token, validates it and then performs a Aws:Sts:AssumeRole based on preconfigured rules.

Aug 8, 2022

Golang Mongodb Jwt Auth Example Using Echo

Golang Mongodb Jwt Auth Example Using Echo

Golang Mongodb Jwt Auth Example Using Echo Golang Mongodb Rest Api Example Using Echo Prerequisites Golang 1.16.x Docker 19.03+ Docker Compose 1.25+ I

Nov 30, 2022

A fast and simple JWT implementation for Go

A fast and simple JWT implementation for Go

JWT Fast and simple JWT implementation written in Go. This package was designed with security, performance and simplicity in mind, it protects your to

Jan 5, 2023

backend implementation demonstration in go with JWT, MongoDB and etc.

backend implementation demonstration in go with JWT, MongoDB and etc.

Nov 19, 2022

Golang implementation of JWT and Refresh Token

Fiber and JWT with Refresh Token Repo ini adalah demostrasi JWT support refresh token tanpa menggunakan storage Branch Main: unlimited refresh token R

Dec 18, 2022

jwt package for gin go applications

gin-jwt jwt package for gin go applications Usage Download using go module: go get github.com/ennaque/gin-jwt Import it in your code: import gwt "gith

Apr 21, 2022

Golang jwt tokens without any external dependency

Yet another jwt lib This is a simple lib made for small footprint and easy usage It allows creating, signing, reading and verifying jwt tokens easily

Oct 11, 2021
Comments
Go-gin-jwt - Secure web api using jwt token and caching mechanism

Project Description This project demonstrate how to create api and secure it wit

Jan 27, 2022
Account-jwt-go - Simple JWT api with go, gorm, gin
Account-jwt-go - Simple JWT api with go, gorm, gin

Account JWT on Go Go, gorm, Gin web framework 를 활용하여 만든 간단한 JWT API 입니다. Dajngo의

Apr 14, 2022
Krakend-jwt-header-rewriter - Kraken Plugin - JWT Header Rewriter

Kraken Plugin - JWT Header Rewriter 1 Plugin Configuration Name Desciption Defau

Feb 15, 2022
:key: Secure alternative to JWT. Authenticated Encrypted API Tokens for Go.

branca branca is a secure alternative to JWT, This implementation is written in pure Go (no cgo dependencies) and implements the branca token specific

Dec 29, 2022
An implementation of JOSE standards (JWE, JWS, JWT) in Go

Go JOSE Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSO

Dec 18, 2022
This is an implementation of JWT in golang!

jwt This is a minimal implementation of JWT designed with simplicity in mind. What is JWT? Jwt is a signed JSON object used for claims based authentic

Oct 25, 2022
This package provides json web token (jwt) middleware for goLang http servers

jwt-auth jwt auth middleware in goLang. If you're interested in using sessions, checkout my sessions library! README Contents: Quickstart Performance

Dec 5, 2022
Golang implementation of JSON Web Tokens (JWT)

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

Jan 6, 2023
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..

loginsrv loginsrv is a standalone minimalistic login server providing a JWT login for multiple login backends. ** Attention: Update to v1.3.0 for Goog

Dec 24, 2022
Simple JWT Golang

sjwt Simple JSON Web Token - Uses HMAC SHA-256 Example // Set Claims claims := New() claims.Set("username", "billymister") claims.Set("account_id", 86

Dec 8, 2022