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.
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"
}
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
}
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
First you need to install the JWT dependency package of Go language:
go get github.com/dgrijalva/jwt- go
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, "" }
}
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!