feature: goctl jwt (#91)

* rebase upstream

* rebase

* trim no need line

* trim no need line

* trim no need line

* update doc

* remove update

* remove no need

* remove no need

* goctl add jwt support

* goctl add jwt support

* goctl add jwt support

* goctl add jwt support

* goctl add jwt support

* goctl add jwt support

* goctl add jwt support

Co-authored-by: kingxt <dream4kingxt@163.com>
master
kingxt 4 years ago committed by GitHub
parent 3e7e466526
commit 5e6dcac734
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -21,26 +21,42 @@ type JwtTokenResponse struct {
RefreshAfter int64 `json:"refresh_after"` // 建议客户端刷新token的绝对时间
}
type GetUserRequest struct {
UserId string `json:"userId"`
}
type GetUserResponse struct {
Name string `json:"name"`
}
service jwt-api {
@server(
handler: JwtHandler
)
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
}
````
再次在生成服务目录中执行:`goctl api go -api jwt.api -dir .`
@server(
jwt: JwtAuth
)
service jwt-api {
@server(
handler: GetUserHandler
)
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) {` 方法如下:
```go
const AccessSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) {
var accessExpire int64 = 60 * 60 * 24 * 7
var accessExpire = l.svcCtx.Config.JwtAuth.AccessExpire
now := time.Now().Unix()
accessToken, err := l.GenToken(now, AccessSecret, nil, accessExpire)
accessToken, err := l.GenToken(now, l.svcCtx.Config.JwtAuth.AccessSecret, nil, accessExpire)
if err != nil {
return nil, err
}
@ -63,7 +79,16 @@ func (l *JwtLogic) GenToken(iat int64, secretKey string, payloads map[string]int
}
```
启动服务器然后测试下获取到的token
在启动服务之前我们需要修改etc/jwt-api.yaml文件如下
```yaml
Name: jwt-api
Host: 0.0.0.0
Port: 8888
JwtAuth:
AccessSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AccessExpire: 604800
```
启动服务器然后测试下获取到的token。
```sh
➜ jwt curl --location --request POST '127.0.0.1:8888/user/token'
@ -74,62 +99,8 @@ func (l *JwtLogic) GenToken(iat int64, secretKey string, payloads map[string]int
### 2 服务器验证JWT token
1. 添加一个测试JWT的路由修改api文件如下
```go
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 {
@server(
handler: JwtHandler
)
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
@server(
handler: GetUserHandler
)
post /user/getUser(GetUserRequest) returns (GetUserResponse)
}
```
再次执行 `goctl api go -api jwt.api -dir .` 生成代码。
2. 修改 routes.go给协议添加JWT认证 `rest.WithJwt(logic.AccessSecret)`
```go
func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) {
engine.AddRoutes([]rest.Route{
{
Method: http.MethodPost,
Path: "/user/token",
Handler: jwtHandler(serverCtx),
},
})
engine.AddRoutes([]rest.Route{
{
Method: http.MethodPost,
Path: "/user/info",
Handler: getUserHandler(serverCtx),
},
}, rest.WithJwt(logic.AccessSecret))
}
```
1. 在api文件中通过`jwt: JwtAuth`标记的service表示激活了jwt认证。
2. 可以阅读rest/handler/authhandler.go文件了解服务器jwt实现。
3. 修改getuserlogic.go如下
```go
@ -165,4 +136,5 @@ http: 200
综上所述基于go-zero的JWT认证完成在真实生产环境部署时候AccessSecret, AccessExpire, RefreshAfter可以通过配置文件配置RefreshAfter 是告诉客户端什么时候该刷新JWT token了一般都需要设置过期时间前几天。
综上所述基于go-zero的JWT认证完成在真实生产环境部署时候AccessSecret, AccessExpire, RefreshAfter根据业务场景通过配置文件配置RefreshAfter 是告诉客户端什么时候该刷新JWT token了一般都需要设置过期时间前几天。

@ -53,7 +53,7 @@ func DoGenProject(apiFile, dir string, force bool) error {
logx.Must(util.MkdirIfNotExist(dir))
logx.Must(genEtc(dir, api))
logx.Must(genConfig(dir))
logx.Must(genConfig(dir, api))
logx.Must(genMain(dir, api))
logx.Must(genServiceContext(dir, api))
logx.Must(genTypes(dir, api, force))

@ -3,8 +3,10 @@ package gogen
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/vars"
)
@ -17,11 +19,18 @@ import {{.authImport}}
type Config struct {
rest.RestConf
{{.auth}}
}
`
jwtTemplate = ` struct {
AccessSecret string
AccessExpire int64
}
`
)
func genConfig(dir string) error {
func genConfig(dir string, api *spec.ApiSpec) error {
fp, created, err := util.MaybeCreateFile(dir, configDir, configFile)
if err != nil {
return err
@ -31,11 +40,18 @@ func genConfig(dir string) error {
}
defer fp.Close()
var authNames = getAuths(api)
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate))
}
var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl)
t := template.Must(template.New("configTemplate").Parse(configTemplate))
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"authImport": authImportStr,
"auth": strings.Join(auths, "\n"),
})
if err != nil {
return nil

@ -180,6 +180,11 @@ func getRoutes(api *spec.ApiSpec) ([]group, error) {
handler: handler,
})
}
if value, ok := apiutil.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
groupedRoutes.authName = value
groupedRoutes.jwtEnabled = true
}
routes = append(routes, groupedRoutes)
}

Loading…
Cancel
Save