diff --git a/doc/jwt.md b/doc/jwt.md index 13e16ff4..77b5ef11 100644 --- a/doc/jwt.md +++ b/doc/jwt.md @@ -16,31 +16,47 @@ type JwtTokenRequest struct { } type JwtTokenResponse struct { - AccessToken string `json:"access_token"` - AccessExpire int64 `json:"access_expire"` + 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) } -```` -再次在生成服务目录中执行:`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了,一般都需要设置过期时间前几天。 + diff --git a/tools/goctl/api/gogen/gen.go b/tools/goctl/api/gogen/gen.go index fd2cc4e0..c5baa10e 100644 --- a/tools/goctl/api/gogen/gen.go +++ b/tools/goctl/api/gogen/gen.go @@ -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)) diff --git a/tools/goctl/api/gogen/genconfig.go b/tools/goctl/api/gogen/genconfig.go index 5beb19ab..a8e634cd 100644 --- a/tools/goctl/api/gogen/genconfig.go +++ b/tools/goctl/api/gogen/genconfig.go @@ -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 diff --git a/tools/goctl/api/gogen/genroutes.go b/tools/goctl/api/gogen/genroutes.go index 74f5d3cb..e77787b2 100644 --- a/tools/goctl/api/gogen/genroutes.go +++ b/tools/goctl/api/gogen/genroutes.go @@ -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) }