Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(四):客户端强类型约束,自动生成 API TS 类型定义
Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(四):客户端强类型约束,自动生成 API TS 类型定义
系列
云原生 API 网关,gRPC-Gateway V2 初探
Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第一篇
Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第二篇
Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务(三):RSA(RS512) 签名 JWT
客户端强类型约束,自动生成 API TS 类型定义
protobufjs
官方文档:protobufjs
安装:
yarn add protobufjs
node_modules/.bin
会多出如下命令:
pbjs
pbts
根据 auth.proto
生成 API TS 类型定义
PROTO_PATH=../microsvcs/auth/api PBTS_BIN_DIR=./node_modules/.bin PBTS_OUT_DIR=./miniprogram/service/proto_gen/auth mkdir -p $PBTS_OUT_DIR$PBTS_BIN_DIR/pbjs -t static -w es6 $PROTO_PATH/auth.proto --no-create --no-encode --no-decode --no-verify --no-delimited -o $PBTS_OUT_DIR/auth_pb_tmp.jsecho 'import * as $protobuf from "protobufjs";\n' > $PBTS_OUT_DIR/auth_pb.js cat $PBTS_OUT_DIR/auth_pb_tmp.js >> $PBTS_OUT_DIR/auth_pb.js rm $PBTS_OUT_DIR/auth_pb_tmp.js$PBTS_BIN_DIR/pbts -o $PBTS_OUT_DIR/auth_pb.d.ts $PBTS_OUT_DIR/auth_pb.js
脚本已被放置在 miniprogram/gen_ts.sh
,在 miniprogram
目录执行 sh gen_ts.sh
即可生成如下文件:
miniprogram/miniprogram/service/proto_gen/auth/auth_pb.js
miniprogram/miniprogram/service/proto_gen/auth/auth_pb.d.ts
修改 app.ts
引入:
import { auth } from "./service/proto_gen/auth/auth_pb"
在文件里面做如下改动:
从上图可以看到有属性提示。这里我们也加入了一个 camelcase-keys
包。它主要用来将属性 key
从网络上传输的 expires_in
转换为 expiresIn
。
Token 验证
编码实战
具体代码位于:microsvcs/shared/auth/token/token.go
type JWTTokenVerifier struct { PublicKey *rsa.PublicKey }func (v *JWTTokenVerifier) Verify(token string) (string, error) { t, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) { return v.PublicKey, nil }) if err != nil { return "", fmt.Errorf("cannot parse token: %v", err) } if !t.Valid { return "", fmt.Errorf("token not valid") } clm, ok := t.Claims.(*jwt.StandardClaims) if !ok { return "", fmt.Errorf("token claim is not StandardClaims") } if err := clm.Valid(); err != nil { return "", fmt.Errorf("claim not valid: %v", err) } return clm.Subject, nil}
测试用例
正常
token
过期坏的
token
签名错误
具体代码位于:microsvcs/shared/auth/token/token_test.go
Refs
API Security : API key is dead..Long live Distributed Token by value
Demo: go-grpc-gateway-v2-microservice
gRPC-Gateway
gRPC-Gateway Docs
我是为少 微信:uuhells123 公众号:黑客下午茶 加我微信(互相学习交流),关注公众号(获取更多学习资料~)
作者:为少
出处:https://www.cnblogs.com/hacker-linner/p/14662182.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。