gozero使用jwt
两个步骤
- 获取token
- 验证token
前端获取token
先编写 jwt.api 文件,放在api目录下
syntax = "v1"info (title: "type title here"desc: "type desc here"author: "type author here"email: "type email here"version: "type version here"
)type JwtTokenRequest {}type JwtTokenResponse {AccessToken string `json:"access_token"`AccessExpire int64 `json:"access_expire"`RefreshAfter int64 `json:"refresh_after"` // 建议客户端刷新token的绝对时间
}type GetUserRequest {UserId string `json:"userId"`
}type GetUserResponse {Name string `json:"name"`
}service jwt-api {@handler JwtHandlerpost /user/token (JwtTokenRequest) returns (JwtTokenResponse)
}@server (jwt: JwtAuth
)
service jwt-api {@handler JwtHandlerspost /user/info (GetUserRequest) returns (GetUserResponse)
}
在api目录下执行
goctl api go -api jwt.api -dir ../
生成如下文件
jwt-api.yaml 文件添加参数 JwtAuth
Name: jwt-api
Host: 0.0.0.0
Port: 8001
JwtAuth:AccessSecret: af5fsdf5a1sd5ga5sd1gAccessExpire: 86400
在zero-jwt目录下执行mod命令
go mod tidy
获取token代码🌰
package logicimport ("context""github.com/golang-jwt/jwt""time""zero-jwt/internal/svc""zero-jwt/internal/types""github.com/zeromicro/go-zero/core/logx"
)type JwtLogic struct {logx.Loggerctx context.ContextsvcCtx *svc.ServiceContext
}func NewJwtLogic(ctx context.Context, svcCtx *svc.ServiceContext) *JwtLogic {return &JwtLogic{Logger: logx.WithContext(ctx),ctx: ctx,svcCtx: svcCtx,}
}func (l *JwtLogic) Jwt(req *types.JwtTokenRequest) (resp *types.JwtTokenResponse, err error) {// todo: add your logic here and delete this linevar accessExpire = l.svcCtx.Config.JwtAuth.AccessExpirenow := time.Now().Unix()accessToken, err := l.GenToken(now, l.svcCtx.Config.JwtAuth.AccessSecret, map[string]interface{}{"uid": 1, "username": "hahah"}, accessExpire)if err != nil {return nil, err}return &types.JwtTokenResponse{AccessToken: accessToken,AccessExpire: now + accessExpire,RefreshAfter: now + accessExpire/2,}, nil
}
func (l *JwtLogic) GenToken(iat int64, secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {claims := make(jwt.MapClaims)claims["exp"] = iat + secondsclaims["iat"] = iatfor k, v := range payloads {claims[k] = v}token := jwt.New(jwt.SigningMethodHS256)token.Claims = claimsreturn token.SignedString([]byte(secretKey))
}
验证获取token里的数据🌰
package logicimport ("context""encoding/json""log""zero-jwt/internal/svc""zero-jwt/internal/types""github.com/zeromicro/go-zero/core/logx"
)type JwtHandlersLogic struct {logx.Loggerctx context.ContextsvcCtx *svc.ServiceContext
}func NewJwtHandlersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *JwtHandlersLogic {return &JwtHandlersLogic{Logger: logx.WithContext(ctx),ctx: ctx,svcCtx: svcCtx,}
}func (l *JwtHandlersLogic) JwtHandlers(req *types.GetUserRequest) (resp *types.GetUserResponse, err error) {//获取token里的数据log.Println(l.ctx.Value("username").(string)) //这里使用(json.Number)强转会报错,username是{}interface 类型log.Println(l.ctx.Value("uid").(json.Number).Int64())return &types.GetUserResponse{Name: "kkkkk" + req.UserId + " " + l.ctx.Value("uid").(json.Number).String() + " " + l.ctx.Value("username").(string)}, nil
}
验证token
发送请求获取token
发送请求验证token
Headers 头部添加 Authorization参数
验证不通过就会报401错误