0
点赞
收藏
分享

微信扫一扫

【Azure 架构师学习笔记】- Power Platform(1) - 简介

玩物励志老乐 2023-12-27 阅读 18

文章目录

初始化项目

#go get github.com/golang-jwt/jwt/v5
go get github.com/dgrijalva/jwt-go

加密

一步一步编写程序

  1. 首先在main()函数中写入
package main

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

func main() {
   
	//jwt.NewWithClaims(Claims)
	jwt.NewWithClaims()
}
package main

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

type MyClaims struct {
   
	jwt.StandardClaims
}

func main() {
   
	//jwt.NewWithClaims(Claims)
	jwt.NewWithClaims()
}

另一个参数–加密方式

package main

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

type MyClaims struct {
   
	UserName string `json:"username"`
	jwt.StandardClaims
}

func main() {
   
	//jwt.NewWithClaims(加密方式,Claims)
	jwt.NewWithClaims(jwt.SigningMethodHS256,MyClaims) //当然这里不能是结构体(MyClaims)而是结构体实例
}

关于StandardClaims

type StandardClaims struct {
   
	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"` //
}
package main

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type MyClaims struct {
   
	UserName string `json:"username"`
	jwt.StandardClaims
}

func main() {
   
	c := MyClaims{
   
		UserName: "AllYourBase",
		StandardClaims: jwt.StandardClaims{
   
			NotBefore: time.Now().Unix() - 60,      //当前时间的一分钟之前生效
			ExpiresAt: time.Now().Unix() + 60*60*2, //当前时间的俩小时
			Issuer:    "AllYourBase",               //用户名
		},
	}
	//jwt.NewWithClaims(加密方式,Claims)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	fmt.Println(token)
}
mySigningKey := []byte("AllYourBase")
//token.SignedString(key)  //key:官方让我们放一个byte
s, err := token.SignedString(mySigningKey)
if err != nil {
   
	fmt.Printf("%s", err)
}
fmt.Println(s)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNoZW4iLCJleHAiOjE3MDMyODk0MzUsImlzcyI6ImNoZW4iLCJuYmYiOjE3MDMyOTY1NzV9.ZeMpAIzPyRoIQSjDctIuQEHxzYRaKQ9McqBfoq3SzCI

生成的这个加密就可以丢给前端去使用了

解密

jwt.ParseWithClaims(token,解析的模板,func(token *jwt.Token)(interface{
   },error){
   })

写法

jwt.ParseWithClaims(s,&MyClaims,func
举报

相关推荐

0 条评论