JWT Certification

Overview

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.

JWT comprises three parts of:headers, payloads, and signatures.

Header usually consists of two parts:token type and the encryption algorithm used.The payload is the main part of the information stored in the token.It includes statements (claims), such as user ID, username, expiry date, etc.Signature is the hash generated using the key after combination of head and payload to verify the authenticity of tokens.

JWT decryption and validation features embedded in go-zero. You can control JWT using optional parameters.

Examples

  1. func main() {
  2. srv := rest.MustNewServer(rest.RestConf{
  3. Port: 8080,
  4. })
  5. srv.AddRoute(rest.Route{
  6. Method: http.MethodGet,
  7. Path: "/hello",
  8. Handler: handle,
  9. }, rest.WithJwt("abc123")/*开启 JWT 功能,并设置 secret 为 abc123 */)
  10. defer srv.Stop()
  11. srv.Start()
  12. }
  13. func handle(w http.ResponseWriter, r *http.Request) {
  14. httpx.OkJson(w, "hello world")
  15. }

JWT Token Generate Example

  1. func getJwtToken(secretKey string, iat, seconds int64,payload string) (string, error) {
  2. claims := make(jwt.MapClaims)
  3. claims["exp"] = iat + seconds
  4. claims["iat"] = iat
  5. claims["payload"] = payload
  6. token := jwt.New(jwt.SigningMethodHS256)
  7. token.Claims = claims
  8. return token.SignedString([]byte(secretKey))
  9. }

JWT Auth Failed Custom Handling Return

Define a callback in main.go

  1. func main() {
  2. ........
  3. server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
  4. // do it yourself
  5. }))
  6. .......
  7. }
JWT Certification - 图1tip

If the JWT authentication fails, an error similar to the following will occur:

  1. HTTP/1.1 401 Unauthorized
  2. Date: Mon, 08 Feb 2023 23:41:57 GMT
  3. Content-Length: 0

JWT Expired Management

The jwt token expired management can be implemented on its own with redis.

References