Use JWT in Go language to implement simple and secure user authentication

王林
Release: 2023-06-15 18:52:08
Original
1812 people have browsed it

With the rapid development of network technology, more and more websites and applications need to implement user authentication functions. However, traditional username and password authentication methods have security risks because they are usually stored in the database. Once the database is attacked, user information will be leaked. In order to solve this problem, JWT (JSON Web Token) came into being. JWT is an open standard (RFC 7519) that defines a simple, self-contained way to transmit information that can be verified and trusted. This article will introduce how to use JWT in Go language to implement simple and secure user authentication.

JWT working principle

Before introducing how to use JWT in Go language, let’s first understand how JWT works. JWT consists of three parts:

  • Header: This part contains token type and algorithm information, usually using SHA256 encryption.
  • Payload: This part stores the information to be transmitted, such as user name, permissions, etc., and can also contain some custom fields.
  • Signature: This part is a signature generated by encrypting a string consisting of Header and Payload.

The token generated by JWT can be passed through HTTP header information or URL parameters. When the client requests the server, the server will check the JWT token in the request header or URL parameters. If the token is valid, it will return the data requested by the client. If the token is invalid, an error message is returned.

In actual applications, the server should set a validity period when generating JWT. After expiration, the client needs to obtain a new JWT token again.

Using JWT in Go language

The JWT function can be quickly and simply implemented in Go language by using a third-party library. This article recommends using the jwt-go library, which supports the generation and verification of JWT and has the advantages of type safety and high performance.

Install jwt-go library

Enter the following command in the terminal. You can use the go get command to install the jwt-go library.

go get github.com/dgrijalva/jwt-go
Copy after login

Generate JWT

In Go language, generating JWT can be achieved through the following code:

package main

import (
    "fmt"
    "time"
    "github.com/dgrijalva/jwt-go"
)

func main() {
    // 创建JWT头信息
    token := jwt.New(jwt.SigningMethodHS256)
    // 设置有效期
    token.Claims = jwt.MapClaims{
        "exp": time.Now().Add(time.Hour * 72).Unix(),
        "iat": time.Now().Unix(),
        "sub": "1234567890",
    }
    // 对生成的JWT令牌进行签名
    signedToken, err := token.SignedString([]byte("secret-key"))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(signedToken)
}
Copy after login

In the code, use the jwt.New() function to create the JWT header information , set the validity period and the transmitted information (in the example, a field named sub is transmitted), and then use the SignedString() function to sign the JWT token.

Verify JWT

In Go language, verifying JWT can be implemented using the following code:

package main

import (
    "fmt"
    "time"
    "github.com/dgrijalva/jwt-go"
)

func main() {
    // 待验证的JWT令牌
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTAzMDAzMTAsImlhdCI6MTYxMDgwNTExMCwic3ViIjoiMTIzNDU2Nzg5MCJ9.5AtrChvChVuWI3TkazGt1mDhbscT8-Qal5U6Qc4dqhc"
    // 解析JWT头信息
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }
        return []byte("secret-key"), nil
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    // 验证JWT有效期
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        expirationTime := time.Unix(int64(claims["exp"].(float64)), 0)
        if expirationTime.Before(time.Now()) {
            fmt.Println("JWT has expired")
        } else {
            fmt.Println("JWT is valid")
        }
    } else {
        fmt.Println("JWT is not valid")
    }
}
Copy after login

In the code, use the jwt.Parse() function to parse the JWT to be verified The token is then verified using the passed signing key. During verification, first use the Claims() function to obtain the validity time in the JWT, and then compare it with the current time. If the token has expired, an error message is returned.

Summary

As a safe and simple authentication method, JWT is widely used in Web development. This article introduces how to use the jwt-go library in the Go language to quickly and simply implement the JWT function. JWT can be used not only for user authentication, but also for data transmission, API authentication and other scenarios. In practical applications, we should pay attention to the validity period of JWT and the security protection of the signing key.

The above is the detailed content of Use JWT in Go language to implement simple and secure user authentication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template