Go Grpc Jwt身份认证

在 http 请求当中我们可以设置 header 用来传递数据,grpc 底层采用 http2 协议也是支持传递数据的,采用的是 metadata。 Metadata 对于 gRPC 本身来说透明, 它使得 client 和 server 能为对方提供本次调用的信息。就像一次 http 请求的 RequestHeader 和 ResponseHeader,http header 的生命周期是一次 http 请求, Metadata 的生命周期则是一次 RPC 调用。在 go 语言中,可以用 grpc.WithPerRPCCredentials 方法来实现。

简单说一下 我的demo吧,一般我们的api有一个login, 会返回token, 然后在请求及其他api的时候 就必须带上这个token。

首先我们创建一个项目文件夹 jwttoken,里面在创建一个api文件夹

1.创建/api/api.proto【为了简单我们没有引入其他的包】

syntax = "proto3";
package api;


service Ping {
  rpc Login (LoginRequest) returns (LoginReply) {}
  rpc SayHello(PingMessage) returns (PingMessage) {}
}

message LoginRequest{
  string username=1;
  string password=2;
}
message LoginReply{
  string status=1;
  string token=2;
}
message PingMessage {
  string greeting = 1;
}

2.编译该文件, 我一般习惯在根目录下操作:

protoc -I api/ -I${GOPATH}/src  --go_out=plugins=grpc:api api/api.proto

3.编写api/handler.go 可以理解是我们日常服务的具体实现:

package api

import (
	"fmt"

	"golang.org/x/net/context"
)

// Server represents the gRPC server
type Server struct {
}

func (s *Server) Login(ctx context.Context, in *LoginRequest) (*LoginReply, error) {
	fmt.Println("Loginrequest: ", in.Username)
	if in.Username == "gavin" && in.Password == "gavin" {
		tokenString := CreateToken(in.Usernam
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值