REST API with JWT
REST API with JWT
Section titled “REST API with JWT”This example demonstrates building a secure REST API with JWT-based authentication using go-zero.
API Definition
Section titled “API Definition”type LoginReq { Username string `json:"username"` Password string `json:"password"`}
type LoginResp { Token string `json:"token"`}
type UserInfoReq {}type UserInfoResp { Id int64 `json:"id"` Name string `json:"name"`}
service user-api { @handler Login post /user/login (LoginReq) returns (LoginResp)
@jwt Auth @handler UserInfo get /user/info (UserInfoReq) returns (UserInfoResp)}Generate Code
Section titled “Generate Code”goctl api go -api user.api -dir .Implement Login Logic
Section titled “Implement Login Logic”func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) { // 1. Validate credentials // 2. Generate JWT token token, err := generateToken(l.svcCtx.Config.Auth.Secret, req.Username) if err != nil { return nil, err } return &types.LoginResp{Token: token}, nil}Configuration
Section titled “Configuration”Name: user-apiHost: 0.0.0.0Port: 8888Auth: AccessSecret: your-secret-key AccessExpire: 86400