接触Golang没多久,今天尝试在Beego框架中用jwt做用户身份验证
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"))
}
编译完,在SignedString
生成token这一步报错 key is of invalid type
time="2020-09-23 15:27:59" level=warning msg="key is of invalid type"
翻了下源码,参数 key 为interface{}
类型,据我了解Golang的空接口应该可以接收任意类型的变量参数,但是问题可能就出在key.([]byte)
这里。
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
}
测试发现,参数key是string
类型,报错 key is of invalid type,换成[]byte
类型,编译通过。不太明白,在网上翻了半天也没有想要答案,最后在官网文档上找到,链接在下边。
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)
}
}
输出结果:
[104 101 108 108 111]
b is an invalid type
参考文档:https://golang.org/doc/effective_go.html#interface_conversions
有疑问加站长微信联系(非本文作者)