jwt-go - The easiest JWT Library that could be the starting point for any of your project

栏目: IT技术 · 发布时间: 3年前

内容简介:The easiest JWT Library that could be the starting point for any of your project.

JWT Go

The easiest JWT Library that could be the starting point for any of 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 very insecure
	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 very insecure
	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 very insecure
	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 very insecure
	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 very insecure
	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 very insecure
	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

You can simply Enable and Disable authorization using code bellow

package main

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

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

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

	// or

	jwt.EnableAuthorization() // Enable authorization
}

Thanks to


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Processing编程学习指南(原书第2版)

Processing编程学习指南(原书第2版)

[美]丹尼尔希夫曼(Daniel Shiffman) / 李存 / 机械工业出版社 / 2017-3-1 / 99.00元

在视觉化界面中学习电脑编程的基本原理! 本书介绍了编程的基本原理,涵盖了创建最前沿的图形应用程序(例如互动艺术、实时视频处理和数据可视化)所需要的基础知识。作为一本实验风格的手册,本书精心挑选了部分高级技术进行详尽解释,可以让图形和网页设计师、艺术家及平面设计师快速熟悉Processing编程环境。 从算法设计到数据可视化,从计算机视觉到3D图形,在有趣的互动视觉媒体和创意编程的背景之......一起来看看 《Processing编程学习指南(原书第2版)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具