欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用go-zero在Go中快速实现JWT认证的步骤详解

程序员文章站 2022-06-22 09:36:30
关于jwt是什么,大家可以看看,一句话介绍下:是可以实现服务器无状态的鉴权认证方案,也是目前最流行的跨域认证解决方案。要实现jwt认证,我们需要分成如下两个步骤 客户端获取jwt token。 服...

关于jwt是什么,大家可以看看,一句话介绍下:是可以实现服务器无状态的鉴权认证方案,也是目前最流行的跨域认证解决方案。

要实现jwt认证,我们需要分成如下两个步骤

  • 客户端获取jwt token。
  • 服务器对客户端带来的jwt token认证。

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

在api文件中通过jwt: jwtauth标记的service表示激活了jwt认证。可以阅读rest/handler/authhandler.go文件了解服务器jwt实现。修改getuserlogic.go如下:

func (l *getuserlogic) getuser(req types.getuserrequest) (*types.getuserresponse, error) {
	return &types.getuserresponse{name: "kim"}, nil
}

我们先不带jwt authorization header请求头测试下,返回http status code是401,符合预期。

➜ 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

加上authorization header请求头测试。

➜ 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了,一般都需要设置过期时间前几天。

3. 项目地址

总结

到此这篇关于如何利用go-zero在go中快速实现jwt认证的文章就介绍到这了,更多相关go-zero实现jwt认证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!