JWT
Overview
In go-zero, we declared HTTP service via api language, and then generated HTTP service code via goctl, after our systematic introduction to API norm.
Service authentication is also a frequently used feature in HTTP service development, this document will describe how to declare intermediate in api files.
JWT
JWT (JSON Web Token) is an open standard (RFC 7519) used to transmit declaratory messages between web applications.It is a lightweight JSON-based authentication and authorization mechanism for the safe transmission of information between clients and servers.
For more documentation about jwt
Let's see how to declare jwt authentication in an api file
syntax = "v1"
type LoginReq {
Username string `json:"username"`
Password string `json:"password"`
}
type LoginResp {
ID string `json:"id"`
Name string `json:"name"`
}
type UserInfoReq {
ID string `json:"id"`
}
type UserInfoResp {
Name string `json:"name"`
}
service user-api {
@handler login
post /user/login (LoginReq) returns (LoginResp)
}
@server (
jwt: Auth // Enable jwt authentication
)
service user-api {
@handler userInfo
post /user/info (UserInfoReq) returns (UserInfoResp)
}
In the above, we declared that the jwt authentication is enabled through the jwt
keyword in @server
, and the jwt authentication is only useful for its corresponding route, as in the jwt above only for /user/info
takes effect, but not for /user/login
, we use Auth
as the value of jwt, after goctl
After code generation, it will be converted into Corresponding to jwt configuration.
Below look briefly at the generated jwt code:
- config.go
- routes.go
package config
import "github.com/zeromicro/go-zero/rest"
type Config struct {
rest.RestConf
Auth struct {// Key and expiration time configuration required for JWT authentication
AccessSecret string
AccessExpire int64
}
}
The Auth field in the Config
structure is the value we declared in the api syntax file, which is the result of code generation
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"go-zero-demo/user/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodPost,
Path: "/user/login",
Handler: loginHandler(serverCtx),
},
},
)
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodPost,
Path: "/user/info",
Handler: userInfoHandler(serverCtx),
},
},
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
)
}
In the above, we can see that our declared jwt
actually generated code by rest.WithJwt
to declare jwt authentication.
takes note of
Jwt authentication after code is generated, the framework only provides server logic and needs to be implemented by the developer for jwt token generation and refresh token.