jwt

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2020 License: MIT Imports: 8 Imported by: 0

README

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:    "asd@asd.com",
		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:    "example@email.com",
		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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DisableAuthorization

func DisableAuthorization()

DisableAuthorization is to Disable the authorization

func EnableAuthorization

func EnableAuthorization()

EnableAuthorization is to enable authorization

func EncryptPassword

func EncryptPassword(password string) ([]byte, error)

EncryptPassword is the function provided to encrypt any password safely

func GenerateJWT

func GenerateJWT(model interface{}) (s string, e error)

GenerateJWT is the function for generate JWT token

func GenerateJWTAndSetExpiredTime

func GenerateJWTAndSetExpiredTime(model interface{}, hours int64, minutes int64, seconds int64) (s string, e error)

GenerateJWTAndSetExpiredTime will generate JWT token alongside with custom expired time

func GetJWTFromEchoHeader

func GetJWTFromEchoHeader(c echo.Context) (token string, err error)

GetJWTFromEchoHeader get JWT from header which provided by echo web framework

func GetJWTFromGinHeader

func GetJWTFromGinHeader(c *gin.Context) (token string, err error)

GetJWTFromGinHeader is to get JWT from header which provided by gin web framework

func GetJWTFromHeader

func GetJWTFromHeader(header string) (token string, err error)

GetJWTFromHeader get JWT from header which provided by any of web framework, but with rules JWT "token"

func GetJWTSecretCode

func GetJWTSecretCode() []byte

GetJWTSecretCode get JWT secret code as a byte

func GetStringJWTSecretCode

func GetStringJWTSecretCode() string

GetStringJWTSecretCode is to get JWT secret code as a string

func IsUseAuthorization

func IsUseAuthorization() bool

IsUseAuthorization is to get status whether use authorization or not

func SetExpiredTime

func SetExpiredTime(hour int64, minute int64, second int64)

SetExpiredTime is to set expired time for JWT session

func SetHMACSigningMethod added in v1.2.0

func SetHMACSigningMethod(s SigningHMAC)

SetHMACSigningMethod is to set signing method globally

func SetJWTSecretCode

func SetJWTSecretCode(secretCode string)

SetJWTSecretCode is to set JWT secret code globally

func VerifyAndBinding

func VerifyAndBinding(model interface{}, t string) (bool, error)

VerifyAndBinding is to verify and binding any given token

func VerifyAndBindingEchoHeader

func VerifyAndBindingEchoHeader(model interface{}, c echo.Context) (token string, isValid bool, err error)

VerifyAndBindingEchoHeader verify and binding the jwt model

func VerifyAndBindingGinHeader

func VerifyAndBindingGinHeader(model interface{}, c *gin.Context) (token string, isValid bool, err error)

VerifyAndBindingGinHeader is to verify and binding the jwt model

func VerifyAndBindingJWT

func VerifyAndBindingJWT(model interface{}, token string) (bool, error)

VerifyAndBindingJWT is the easy way to verify and binding JWT token at the same time

func VerifyEchoHeader

func VerifyEchoHeader(c echo.Context) (string, bool, error)

VerifyEchoHeader only verify echo header

func VerifyGinHeader

func VerifyGinHeader(c *gin.Context) (string, bool, error)

VerifyGinHeader is the function that only verify gin header

func VerifyJWT

func VerifyJWT(token string) (bool, error)

VerifyJWT is the function for verify any generated JWT token

func VerifyPassword

func VerifyPassword(encryptedPassword string, password string) (bool, error)

VerifyPassword is the function for verify between encryption password and requested password

Types

type Authorization

type Authorization struct {
	Username string `form:"username" json:"username" xml:"username" binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

Authorization is the default authorization model

func (Authorization) GenerateJWT

func (auth Authorization) GenerateJWT() (string, error)

GenerateJWT is to generate JWT token by authorization model

func (Authorization) GenerateJWTAndSetExpiredTime

func (auth Authorization) GenerateJWTAndSetExpiredTime(hour int64, minute int64, seconds int64) (string, error)

GenerateJWTAndSetExpiredTime generate JWT token by authorization model also set the expired time manually

func (Authorization) GetPasswordEncryption

func (auth Authorization) GetPasswordEncryption() ([]byte, error)

GetPasswordEncryption is to create password encryption using bcrypt

func (Authorization) GetStringPasswordEncryption

func (auth Authorization) GetStringPasswordEncryption() (string, error)

GetStringPasswordEncryption is to create password encryption using bcrypt and string as the result

func (Authorization) VerifyEncryptedPassword added in v1.3.0

func (auth Authorization) VerifyEncryptedPassword(password string) (bool, error)

VerifyEncryptedPassword is the fastest way to verify encrypted password stored in database

func (Authorization) VerifyJWT

func (auth Authorization) VerifyJWT(token string) (bool, error)

VerifyJWT is the simply way to check authorization

func (Authorization) VerifyPassword

func (auth Authorization) VerifyPassword(password string) (bool, error)

VerifyPassword is the fastest way to verify password

type CustomClaims

type CustomClaims struct {
	Object interface{}
	jwt.StandardClaims
}

CustomClaims is the model provided by this library

type SigningHMAC added in v1.2.0

type SigningHMAC struct {
	Method *jwt.SigningMethodHMAC
}

SigningHMAC is type of signing that can be used for signing and validation JWT

func GetHMACSigningMethod added in v1.2.0

func GetHMACSigningMethod() SigningHMAC

GetHMACSigningMethod is to get signing method

func HS256 added in v1.2.0

func HS256() SigningHMAC

HS256 is type of SigningHMAC method

func HS384 added in v1.2.0

func HS384() SigningHMAC

HS384 is type of SigningHMAC method

func HS512 added in v1.2.0

func HS512() SigningHMAC

HS512 is type of SigningHMAC method

Jump to

Keyboard shortcuts

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