教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang中使用 jwt生成token报错:key is of invalid type

Golang中使用 jwt生成token报错:key is of invalid type

发布时间:2022-02-28   编辑:jiaochengji.com
教程集为您提供Golang中使用 jwt生成token报错:key is of invalid type等资源,欢迎您收藏本站,我们将为您提供最新的Golang中使用 jwt生成token报错:key is of invalid type资源

接触Golang没多久,今天尝试在Beego框架中用jwt做用户身份验证

<pre><code class="lang-go hljs">package controllers import ( "fmt" "github.com/astaxie/beego" "github.com/dgrijalva/jwt-go" "github.com/sirupsen/logrus" "time" ) type LoginController struct { beego.Controller } type LoginForm struct { Username string `form:"username"` Password string `form:"password"` } func init() { logrus.SetFormatter(&logrus.TextFormatter{ TimestampFormat: "2006-01-02 15:04:05", }) } func (c *LoginController) Login() { token, err := generateToken() if err != nil logrus.Warn(err) } fmt.Println(token) } func generateToken() (string, error) { type CustomClaims struct { id int jwt.StandardClaims } jwtttl, err := beego.AppConfig.Int("jwt_ttl") if err != nil { logrus.Println(err) } token := jwt.NewWithClaims(jwt.SigningMethodHS256, CustomClaims{ 1, jwt.StandardClaims{ // 设置过期时间 ExpiresAt: time.Now().Add(time.Duration(jwtttl)).Unix(), }, }) return token.SignedString(beego.AppConfig.String("jwt_secret")) } </code></code></pre>

编译完,在<code>SignedString</code>生成token这一步报错 key is of invalid type

<pre><code class="lang-console hljs">time="2020-09-23 15:27:59" level=warning msg="key is of invalid type" </code></code></pre>

翻了下源码,参数 key 为<code>interface{}</code>类型,据我了解Golang的空接口应该可以接收任意类型的变量参数,但是问题可能就出在<code>key.([]byte)</code>这里。

<pre><code class="lang-go hljs">func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { if keyBytes, ok := key.([]byte); ok { if !m.Hash.Available() { return "", ErrHashUnavailable } hasher := hmac.New(m.Hash.New, keyBytes) hasher.Write([]byte(signingString)) return EncodeSegment(hasher.Sum(nil)), nil } return "", ErrInvalidKeyType } </code></code></pre>

测试发现,参数key是<code>string</code>类型,报错 key is of invalid type,换成<code>[]byte</code>类型,编译通过。不太明白,在网上翻了半天也没有想要答案,最后在官网文档上找到,链接在下边。

<pre><code class="lang-go hljs">package main import "fmt" func main() { var a interface{} var b interface{} a = []byte("hello") b = "hello" key, ok := a.([]byte) if !ok { fmt.Println("a is an invalid type") } else { fmt.Println(key) } key, ok = b.([]byte) if !ok { fmt.Println("b is an invalid type") } else { fmt.Println(key) } } </code></code></pre>

输出结果:

<pre><code class="lang-go hljs">[104 101 108 108 111] b is an invalid type </code></code></pre>

参考文档:https://golang.org/doc/effective_go.html#interface_conversions

到此这篇关于“ Golang中使用 jwt生成token报错:key is of invalid type”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Golang中使用 jwt生成token报错:key is of invalid type
Golang 实现JWT认证
JWT 在 Gin 中的使用
JWT实现用户认证原理与实现(golang)
JWT Token认证
Golang map 三板斧第二式:注意事项
go-kratos 微服务框架 bm 模块使用
Slice实现原理分析
Golang 需要避免踩的 50 个坑(一)
Go 语言从入门到精通

[关闭]
~ ~