golang jwt 签署令牌Authentication token
- go
- 2024-09-05
- 255热度
- 0评论
1.要安装 jwt 包,首先需要 安装Go,然后可以使用下面的命令将其添加jwt-go为 Go 程序中的依赖项。
go get -u github.com/golang-jwt/jwt/v5
2.将其导入到您的代码中:
import "github.com/golang-jwt/jwt/v5"
3.demo
func Test(t *testing.T) {
//商户
subject := "01H"
// 密钥
secretBase64 := "AwFj+OTCI="
secret, err := base64.StdEncoding.DecodeString(secretBase64)
if err != nil {
log.Fatalf("Error decoding base64 secret: %v", err)
}
// 过期秒数
expirseIn := 60 * time.Second
// 创建jwt token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": subject,
"exp": time.Now().Add(expirseIn).Unix(),
})
// 使用密钥签名
tokenString, err := token.SignedString(secret)
if err != nil {
log.Fatalf("Error signing token: %v", err)
}
fmt.Println("tokenString=", tokenString)
m := make(map[string]interface
m["username"] = "www"
m["payer"] = "qqq"
// 将数据转为JSON格式
jsonData, err := json.Marshal(m)
if err != nil {
log.Fatalf("Error marshalling JSON: %v", err)
}
client := &http.Client{}
url := "https://demo.com"
method := "POST"
req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatalf("Error creating request: %v", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tokenString))
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error sending request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response body: %v", err)
}
log.Printf("Response body: %s", string(body))
}
log.Printf("Response StatusCode: %d,%d", resp.StatusCode,http.StatusOK)
info := TestRespone{}
err = ffjson.Unmarshal(body, &info)
if err != nil {
log.Printf("body Unmarshal Err %v", err)
}
log.Printf("info.Code======%s",info.Code)
}