我想检查我们的服务器是否生成了 JWT?我使用 JWT 进行身份验证并使用 RS256 作为 JWT 的算法现在,我想在 Golang 中编写一个函数来验证 JWT 令牌是否属于我们。下面是我实现的代码: publicKey = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAxxxxxxf2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTB\nfQIDAQAB\n-----END PUBLIC KEY-----\n" // sample token string taken from the New example tokenString := this.JWT[0] claims := jwt.MapClaims{} token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { return []byte(publicKey), nil }) // ... error handling if err != nil { fmt.Println(err) } fmt.Println("TOKEN is:", token.Valid) // do something with decoded claims for key, val := range claims { fmt.Printf("Key: %v, value: %v\n", key, val) }这是输出:-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvs97nrY4XqXVJT1Y4AU5xxxTLWXK2H4swuXSEyV75Ylem+f2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTBfQIDAQAB-----END PUBLIC KEY-----key is of invalid typeTOKEN is: falseKey: iss, value: https://example.comKey: nbf, value: 1.592797834e+09Key: exp, value: 1.592801434e+09Key: sub, value: 3Key: aid, value: 2Key: fea, value: 0Key: iat, value: 1.592797834e+09Key: aud, value: []Key: jti, value: 7a97a2327e671d2bf01253819fb319d6我观察到key is of invalid type并且token.valid是false。谁能帮我指出错误的代码以及如何解决这个问题?
2 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
从公钥中删除换行符并尝试一下。
publicKey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAxxxxxxf2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTBfQIDAQAB-----END PUBLIC KEY-----"
- 2 回答
- 0 关注
- 163 浏览
添加回答
举报
0/150
提交
取消