Home  >  Article  >  Backend Development  >  Go language server programming practice: using JWT to protect API interfaces

Go language server programming practice: using JWT to protect API interfaces

WBOY
WBOYOriginal
2023-06-18 16:55:281105browse

In today's Internet era, with the popularity of Web applications, API (Application Programming Interface, application programming interface) has attracted more and more attention and dependence from developers. And protecting the security of API interface is a very important issue. This article will take Go language as an example to introduce how to use JWT (JSON Web Token) to protect the security of API interfaces.

1. What is JWT

The full name of JWT is JSON Web Token, which is an open standard (RFC 7519) used to transmit secure information between parties. JWT can authenticate, authorize and exchange information. JWT is commonly used to pass authentication information in web applications or APIs.

In JWT, it consists of three parts: header, payload and signature.

  1. Header

The header usually consists of two parts: the type of token (i.e. JWT) and the algorithm name (such as HMAC SHA256 or RSA).

{
"alg": "HS256",
"typ": "JWT"
}

  1. Payload

The payload contains some reliable and useful information, such as user ID or access permissions. Custom claims can be added to the payload (it is recommended to only use registered claim names).

{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}

  1. Signature

In order to verify whether the JWT is authentic and valid, the JWT needs to be signed using the key and the algorithm specified in the header.

HMACSHA256(
base64UrlEncode(header) "."
base64UrlEncode(payload),
your-256-bit-secret
)

2. Use JWT Protect API interface

  1. Install JWT dependencies

First you need to install the JWT dependency package of Go language:

go get github.com/dgrijalva/jwt- go

  1. JWT generation and verification

When using JWT to protect the API interface, you need to generate and verify JWT. The following is a simple example code to generate and verify JWT:

Generate JWT

func GenerateToken(userid string) (string, error) {

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "userid": userid,
    "exp":   time.Now().Add(time.Hour * 24 * 7).Unix(), //有效期一周
})
tokenString, err := token.SignedString([]byte("mysecretkey"))
if err != nil {
    return "", err
}
return tokenString, nil

}

Verify JWT

func ValidateToken(tokenString string) (bool, string) {

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    return []byte("mysecretkey"), nil
})
if err == nil && token.Valid {
    claims := token.Claims.(jwt.MapClaims)
    userid := claims["userid"].(string) //取出userid
    return true, userid
} else {
    return false, ""
}

}

  1. Use the JWT verification mechanism in the API interface

In the API interface, you need to read the JWT from the HTTP request first and verify it. If the verification passes, access to the API interface is allowed, otherwise a 403 error (no permission) is returned.

The following is a sample code:

func myAPIHandler(w http.ResponseWriter, r *http.Request) {

tokenString := r.Header.Get("Authorization") //从HTTP请求中获取JWT
if tokenString == "" {
    w.WriteHeader(http.StatusForbidden)
    return
}
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
ok, userid := ValidateToken(tokenString) //校验JWT
if !ok {
    w.WriteHeader(http.StatusForbidden)
    return
}
// 对于登录用户,可以从JWT中获取用户信息(例如userid),并进行权限控制
// ...
// 处理API请求
// ...

}

3. Summary

Using JWT can effectively protect the security of the API interface and ensure that only authorized users can access the API interface. In Go language, using JWT is also very simple. You only need to install dependency packages and write corresponding code. At the same time, in order to protect the security of the API interface, other security measures are also required, such as HTTPS encryption, firewall settings, log monitoring, etc.

The above is the detailed content of Go language server programming practice: using JWT to protect API interfaces. 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