关于golang:如何利用gozero在Go中快速实现JWT认证

12次阅读

共计 2947 个字符,预计需要花费 8 分钟才能阅读完成。

对于 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

  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
}
  • 咱们先不带 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. 我的项目地址

https://github.com/tal-tech/go-zero

好将来技术

正文完
 0