Home  >  Article  >  Backend Development  >  Best practices for authentication using JWT in Go

Best practices for authentication using JWT in Go

王林
王林Original
2023-06-17 12:54:102337browse

With the popularity of Web applications and the expansion of their application scope, it is increasingly important to protect user data and identity information. Authentication in applications is very necessary. This article will introduce the best practices on how to use JWT to implement authentication in Go language.

What is JWT

JWT is the abbreviation of JSON Web Token. It is an authentication mechanism that can safely transmit information without requiring storage methods such as cookies.

A JWT consists of three parts:

  • Header: Contains information such as algorithm and type.
  • Payload: Stores the user information to be passed, such as user name, ID, etc.
  • Signature: The signature generated by Header, Payload and key ensures that the JWT has not been tampered with.

When the user logs in, the server will verify the user's information. If it passes, the server will generate a JWT and return it to the client. When the client accesses other resources again, it needs to carry the JWT to For user authentication on the server side, this avoids the need to authenticate and store the Session for each request.

How to use JWT to implement authentication in Go language

Installation

To use JWT, you need to install related packages. In the Go language, the official package github.com/dgrijalva/jwt-go is provided, which can be easily used.

go get github.com/dgrijalva/jwt-go

Create JWT token

We can create JWT token using the following code

func createToken() string {
    token := jwt.New(jwt.SigningMethodHS256)
    claims := token.Claims.(jwt.MapClaims)
    claims["name"] = "张三"
    claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // 1天过期
    tokenString, _ := token.SignedString([]byte("自定义密钥"))
    return tokenString
}

jwt.New(jwt.SigningMethodHS256) is used to create JWT token instance, where jwt.SigningMethodHS256 means using the HS256 algorithm.

The Claims type of a token instance is a map. Customized data can be stored in the token by adding information to the map. When authenticating, the data in the Payload can be obtained.

In Claims, we defined the user information and expiration time by adding "name" and "exp", and then we generated the JWT token by signing with the key.

Parsing JWT token

When the client sends a JWT token to the server, the server needs to check the validity of the JWT token and parse it to obtain user information.

func parseToken(tokenString string) {
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("预期的签名方法不正确:%v", token.Header["alg"])
        }
        return []byte("自定义密钥"), nil
    })
    if err != nil {
        fmt.Println("JWT解析失败")
        return
    }
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        fmt.Println(claims["name"], claims["exp"])
    } else {
        fmt.Println("无效的JWT令牌")
    }
}

In the code, cast type conversiontoken.Claims.(jwt.MapClaims)Get jwt.Claims in map form and verify it.

We also need to provide a key (here "custom key") to verify the signature to ensure that it has not been tampered with during transmission.

If the JWT token verification passes, you can obtain information from Claims, including custom data stored in the token.

JWT usage example

The following is a complete Go example showing the complete process of creating JWT tokens and parsing JWT tokens.

package main

import (
    "fmt"
    "time"

    "github.com/dgrijalva/jwt-go"
)

func main() {
    // 创建JWT令牌
    token := jwt.New(jwt.SigningMethodHS256)
    claims := token.Claims.(jwt.MapClaims)
    claims["name"] = "张三"
    claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

    // 签名密钥
    tokenString, _ := token.SignedString([]byte("自定义密钥"))
    fmt.Println("JWT创建成功", tokenString)

    // 解析JWT令牌
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("预期的签名方法不正确:%v", token.Header["alg"])
        }
        return []byte("自定义密钥"), nil
    })
    if err != nil {
        fmt.Println("JWT解析失败")
        return
    }
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        fmt.Println("JWT解析成功", claims["name"], claims["exp"])
    } else {
        fmt.Println("无效的JWT令牌")
    }
}

Summary

Authentication in web applications is very necessary. Using JWT credentials can reduce server-side processing overhead and improve performance. It is also a more secure and reliable authentication mechanism. In the Go language, using JWT is very convenient and can be easily implemented through the related package github.com/dgrijalva/jwt-go.

In short, JWT is a very good authentication method. Using JWT can protect the security of user data and identity information, and improve the performance and reliability of web applications.

The above is the detailed content of Best practices for authentication using JWT in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn