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>
This commit is contained in:
144
doc/jwt.md
144
doc/jwt.md
@@ -15,71 +15,6 @@
|
|||||||
type JwtTokenRequest struct {
|
type JwtTokenRequest struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type JwtTokenResponse struct {
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
AccessExpire int64 `json:"access_expire"`
|
|
||||||
RefreshAfter int64 `json:"refresh_after"` // 建议客户端刷新token的绝对时间
|
|
||||||
}
|
|
||||||
|
|
||||||
service jwt-api {
|
|
||||||
@server(
|
|
||||||
handler: JwtHandler
|
|
||||||
)
|
|
||||||
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
|
|
||||||
}
|
|
||||||
````
|
|
||||||
|
|
||||||
再次在生成服务目录中执行:`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
|
|
||||||
|
|
||||||
now := time.Now().Unix()
|
|
||||||
accessToken, err := l.GenToken(now, 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))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
启动服务器,然后测试下获取到的token
|
|
||||||
|
|
||||||
```sh
|
|
||||||
➜ jwt 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. 添加一个测试JWT的路由,修改api文件如下:
|
|
||||||
|
|
||||||
```go
|
|
||||||
type JwtTokenRequest struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
type JwtTokenResponse struct {
|
type JwtTokenResponse struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
AccessExpire int64 `json:"access_expire"`
|
AccessExpire int64 `json:"access_expire"`
|
||||||
@@ -99,37 +34,73 @@ service jwt-api {
|
|||||||
handler: JwtHandler
|
handler: JwtHandler
|
||||||
)
|
)
|
||||||
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
|
post /user/token(JwtTokenRequest) returns (JwtTokenResponse)
|
||||||
|
}
|
||||||
|
|
||||||
|
@server(
|
||||||
|
jwt: JwtAuth
|
||||||
|
)
|
||||||
|
service jwt-api {
|
||||||
@server(
|
@server(
|
||||||
handler: GetUserHandler
|
handler: GetUserHandler
|
||||||
)
|
)
|
||||||
post /user/getUser(GetUserRequest) returns (GetUserResponse)
|
post /user/info(GetUserRequest) returns (GetUserResponse)
|
||||||
}
|
}
|
||||||
```
|
````
|
||||||
|
|
||||||
再次执行 `goctl api go -api jwt.api -dir .` 生成代码。
|
在服务jwt目录中执行:`goctl api go -api jwt.api -dir .`
|
||||||
|
打开jwtlogic.go文件,修改 `func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) {` 方法如下:
|
||||||
2. 修改 routes.go,给协议添加JWT认证 `rest.WithJwt(logic.AccessSecret)`
|
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) {
|
|
||||||
engine.AddRoutes([]rest.Route{
|
func (l *JwtLogic) Jwt(req types.JwtTokenRequest) (*types.JwtTokenResponse, error) {
|
||||||
{
|
var accessExpire = l.svcCtx.Config.JwtAuth.AccessExpire
|
||||||
Method: http.MethodPost,
|
|
||||||
Path: "/user/token",
|
now := time.Now().Unix()
|
||||||
Handler: jwtHandler(serverCtx),
|
accessToken, err := l.GenToken(now, l.svcCtx.Config.JwtAuth.AccessSecret, nil, accessExpire)
|
||||||
},
|
if err != nil {
|
||||||
})
|
return nil, err
|
||||||
engine.AddRoutes([]rest.Route{
|
}
|
||||||
{
|
|
||||||
Method: http.MethodPost,
|
return &types.JwtTokenResponse{AccessToken: accessToken, AccessExpire: now + accessExpire, RefreshAfter: now + accessExpire/2}, nil
|
||||||
Path: "/user/info",
|
}
|
||||||
Handler: getUserHandler(serverCtx),
|
|
||||||
},
|
func (l *JwtLogic) GenToken(iat int64, secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {
|
||||||
}, rest.WithJwt(logic.AccessSecret))
|
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文件如下:
|
||||||
|
```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'
|
||||||
|
{"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如下:
|
3. 修改getuserlogic.go如下:
|
||||||
|
|
||||||
```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(util.MkdirIfNotExist(dir))
|
||||||
logx.Must(genEtc(dir, api))
|
logx.Must(genEtc(dir, api))
|
||||||
logx.Must(genConfig(dir))
|
logx.Must(genConfig(dir, api))
|
||||||
logx.Must(genMain(dir, api))
|
logx.Must(genMain(dir, api))
|
||||||
logx.Must(genServiceContext(dir, api))
|
logx.Must(genServiceContext(dir, api))
|
||||||
logx.Must(genTypes(dir, api, force))
|
logx.Must(genTypes(dir, api, force))
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ package gogen
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
"text/template"
|
"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/api/util"
|
||||||
"github.com/tal-tech/go-zero/tools/goctl/vars"
|
"github.com/tal-tech/go-zero/tools/goctl/vars"
|
||||||
)
|
)
|
||||||
@@ -17,11 +19,18 @@ import {{.authImport}}
|
|||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
rest.RestConf
|
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)
|
fp, created, err := util.MaybeCreateFile(dir, configDir, configFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -31,11 +40,18 @@ func genConfig(dir string) error {
|
|||||||
}
|
}
|
||||||
defer fp.Close()
|
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)
|
var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl)
|
||||||
t := template.Must(template.New("configTemplate").Parse(configTemplate))
|
t := template.Must(template.New("configTemplate").Parse(configTemplate))
|
||||||
buffer := new(bytes.Buffer)
|
buffer := new(bytes.Buffer)
|
||||||
err = t.Execute(buffer, map[string]string{
|
err = t.Execute(buffer, map[string]string{
|
||||||
"authImport": authImportStr,
|
"authImport": authImportStr,
|
||||||
|
"auth": strings.Join(auths, "\n"),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -180,6 +180,11 @@ func getRoutes(api *spec.ApiSpec) ([]group, error) {
|
|||||||
handler: handler,
|
handler: handler,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if value, ok := apiutil.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
|
||||||
|
groupedRoutes.authName = value
|
||||||
|
groupedRoutes.jwtEnabled = true
|
||||||
|
}
|
||||||
routes = append(routes, groupedRoutes)
|
routes = append(routes, groupedRoutes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user