2 回答
TA贡献1848条经验 获得超6个赞
我使用这个库在 Go 中签署 JWT:github.com/dgrijalva/jwt-go,然后我像这样检查它:
reqToken := r.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer")
if len(splitToken) != 2 {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "No se ha proporcionado el token")
return
}
reqToken = strings.TrimSpace(splitToken[1])
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(reqToken, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "No autenticado")
return
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "No autenticado")
return
}
if !tkn.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
- 2 回答
- 0 关注
- 200 浏览
添加回答
举报