golang JWT authentication token packet

Introduction

JWT:

  • json web token, is a specification
  • It consists of three parts
    • Header head
    • Payload PayLoad
    • Signature Signature
  • Use . To upper portion 3 is connected
  • “Token” : Header+"."+PayLoad+"."+Signature
Header

Header action is used to indicate the encryption algorithm used to sign the

{
	"typ":"JWT",
	"alg":"HS256"lag
}

Change typically will first Base64 encoded data after splicing json

PayLoad

Payload for storing some of the information, which should contain claims

claims
Audience string `json:"aud,omitempty"`  
ExpiresAt int64 `json:"exp,omitempty"`  
Id string `json:"jti,omitempty"` 
IssuedAt int64 `json:"iat,omitempty"`  
Issuer string `json:"iss,omitempty"`  
NotBefore int64 `json:"nbf,omitempty"`  
Subject string `json:"sub,omitempty"`
1. aud 标识token的接收者.
2. exp 过期时间.通常与Unix UTC时间做对比过期后token无效
3. jti 是自定义的id号 
4. iat 签名发行时间.
5. iss 是签名的发行者.
6. nbf 这条token信息生效时间.这个值可以不设置,但是设定后,一定要大于当前Unix UTC,否则token将会延迟生效.
7. sub 签名面向的用户

Wherein, if the definition expand iatthen using the back jwt.Parse()when, it will automatically check whether expired

After the first payload also generally Base64 encoding before subsequent splicing

Signature

Encryption algorithms and application Header Header Payload JSON data (typically the private key plus user-defined) by

JWT包

go get github.com/dgrijalva/jwt-go

use

Generate a token
import (
	"time"
	"github.com/dgrijalva/jwt-go"
)

var key string = "key"

func GenerateToken() (string, error) {
	token := jwt.new(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["sub"] = 1 //用于在controller中确定用户
	claims["exp"] = time.Now().Add(time.Hour.Truncate(72)) //设置过期时间为72小时后
	clamis["iat"] = time.Now().Unix()//用作和exp对比的时间
	token.Claims = claims

	tokenString, err := token.SignedString([]byte(key))
	if err != nil {
		return nil, err
	}
	return tokenString, nil
}
Verification token

Generally used as middleware to verify whether the user is legal

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var key string = "key"

func AuthCheck(tokenString string) bool {
	token := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error)) {
	//验证是否是给定的加密算法
	_, ok := token.Method.(*jwt.SigningMethodHMAC)
	if !ok {
		return false
	}
	return []byte(key)
  })
	if !token.Valid {
		return false
	} else {
		claims := token.Claims.(jwt.MapClaims)
		fmt.Println(claims["sub"])
		return true
	}
}

At last

Token generated like this

eyJfasghabgdsgI1NiIsInRfasfaVCJ9.eyJleHAiOjE1NDA2MDgyODgsdasaI6IllEUgasgasdaiwiYWRtaW4iOnRydWV9.8wE-_Wx-DHIqweXJ9KT5JOdasCEaUNEIGDy9CUbM
Published 48 original articles · won praise 56 · views 20000 +

Guess you like

Origin blog.csdn.net/zhetmdoubeizhanyong/article/details/102568887