[zeromicro/go-zero]JWT token 生成!'key 类型无效'

2024-08-24 955 views
1

指南->业务开发->演示项目下载

我下载了 demo,配置了参数,但是运行 getJwtToken() 却返回错误:'Key is of invalid type'。这是为什么?

用户-api.yaml:

Name: user-api
Host: 0.0.0.0
Port: 8888
Mysql:
  Datasource: root:@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
CacheRedis:
  - Host: 127.0.0.1:6379
    Pass:
    Type: node
Auth:
  AccessSecret: hello231asdf
  AccessExpire: 3600

调试:添加 fmt.Println(secretKey)

func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds, userId int64) (string, error) {
    claims := make(jwt.MapClaims)
    claims["exp"] = iat + seconds
    claims["iat"] = iat
    claims["userId"] = userId
    token := jwt.New(jwt.SigningMethodES256)
    fmt.Println(secretKey)
    token.Claims = claims
    return token.SignedString([]byte(secretKey))
}

然后:

 curl -i -X POST \
  http://127.0.0.1:8888/user/login \
  -H 'Content-Type: application/json' \
  -d '{
    "username":"666",
    "password":"123456"
}'

结果和user-api.yaml中的Auth一致

Starting server at 0.0.0.0:8888...
hello231asdf
......

我哪里做错了?

回答

9

我不明白问题出在哪里。我的代码运行正常。你能给出一个演示吗?

6

secretKey将类型更改为[]byte,不要使用string

6

事实上secretKey已经被改变了。

return token.SignedString([]byte(secretKey))