怎么利用go-zero在Go中实现JWT认证

发布时间:2021-09-16 18:14:23 作者:小新
来源:亿速云 阅读:172

这篇文章主要介绍了怎么利用go-zero在Go中实现JWT认证,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

1. 客户端获取JWT Token

我们定义一个协议供客户端调用获取JWT token,我们新建一个目录jwt然后在目录中执行 goctl api -o jwt.api,将生成的jwt.api改成如下:

type JwtTokenRequest struct {
}

type JwtTokenResponse struct {
  AccessToken  string `json:"access_token"`
  AccessExpire int64  `json:"access_expire"`
  RefreshAfter int64  `json:"refresh_after"` // 建议客户端刷新token的绝对时间
}

type GetUserRequest struct { 
  UserId string `json:"userId"`
}

type GetUserResponse struct {
  Name string `json:"name"`
}

service jwt-api {
  @handler JwtHandler
  post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
}

@server(
  jwt: JwtAuth
)
service jwt-api {
  @handler JwtHandler
  post /user/info(GetUserRequest) returns (GetUserResponse)
}

在服务jwt目录中执行:goctl api go -api jwt.api -dir . 打开jwtlogic.go文件,修改 func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) { 方法如下:

func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) {
	var accessExpire = l.svcCtx.Config.JwtAuth.AccessExpire

	now := time.Now().Unix()
	accessToken, err := l.GenToken(now, l.svcCtx.Config.JwtAuth.AccessSecret, nil, 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 + seconds
	claims["iat"] = iat
	for k, v := range payloads {
		claims[k] = v
	}

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

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

在启动服务之前,我们需要修改etc/jwt-api.yaml文件如下:

Name: jwt-api
Host: 0.0.0.0
Port: 8888
JwtAuth:
  AccessSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  AccessExpire: 604800

启动服务器,然后测试下获取到的token。

➜ curl --location --request POST '127.0.0.1:8888/user/token'
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc","access_expire":1601261429,"refresh_after":1600959029}

2. 服务器验证JWT token

  1. 在api文件中通过jwt: JwtAuth标记的service表示激活了jwt认证。

  2. 可以阅读rest/handler/authhandler.go文件了解服务器jwt实现。

  3. 修改getuserlogic.go如下:

func (l *GetUserLogic) GetUser(req types.GetUserRequest) (*types.GetUserResponse, error) {
	return &types.GetUserResponse{Name: "kim"}, nil
}
➜ curl -w  "\nhttp: %{http_code} \n" --location --request POST '127.0.0.1:8888/user/info' \
--header 'Content-Type: application/json' \
--data-raw '{
    "userId": "a"
}'

http: 401
➜ curl -w  "\nhttp: %{http_code} \n" --location --request POST '127.0.0.1:8888/user/info' \
--header 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDEyNjE0MjksImlhdCI6MTYwMDY1NjYyOX0.6u_hpE_4m5gcI90taJLZtvfekwUmjrbNJ-5saaDGeQc' \
--header 'Content-Type: application/json' \
--data-raw '{
    "userId": "a"
}'
{"name":"kim"}
http: 200

综上所述:基于go-zero的JWT认证完成,在真实生产环境部署时候,AccessSecret, AccessExpire, RefreshAfter根据业务场景通过配置文件配置,RefreshAfter 是告诉客户端什么时候该刷新JWT token了,一般都需要设置过期时间前几天。

感谢你能够认真阅读完这篇文章,希望小编分享的“怎么利用go-zero在Go中实现JWT认证”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. 怎么在Vue路由中实现JWT身份认证
  2. 怎么在Node.js中利用Koa实现JWT用户认证

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go jwt

上一篇:.NET2.0环境下的Ajax选型和应用

下一篇:Kafka中的基本概念图解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》