Go-jose: An Implementation Of JOSE Standards (JWE, JWS, JWT) in Go

Go JOSE

Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSON Web Encryption, JSON Web Signature, and JSON Web Token standards.

Disclaimer: This library contains encryption software that is subject to the U.S. Export Administration Regulations. You may not export, re-export, transfer or download this code or any part of it in violation of any United States law, directive or regulation. In particular this software may not be exported or re-exported in any form or on any media to Iran, North Sudan, Syria, Cuba, or North Korea, or to denied persons or entities mentioned on any US maintained blocked list.

Overview

The implementation follows the JSON Web Encryption (RFC 7516), JSON Web Signature (RFC 7515), and JSON Web Token (RFC 7519) specifications. Tables of supported algorithms are shown below. The library supports both the compact and JWS/JWE JSON Serialization formats, and has optional support for multiple recipients. It also comes with a small command-line utility (jose-util) for dealing with JOSE messages in a shell.

Note: We use a forked version of the encoding/json package from the Go standard library which uses case-sensitive matching for member names (instead of case-insensitive matching). This is to avoid differences in interpretation of messages between go-jose and libraries in other languages.

Versions

Version 2 (branch, doc) is the current stable version:

import "gopkg.in/square/go-jose.v2"

Version 3 (branch, doc) is the under development/unstable version (not released yet):

import "github.com/go-jose/go-jose/v3"

All new feature development takes place on the master branch, which we are preparing to release as version 3 when it's ready. Version 2 will continue to receive critical bug and security fixes. Note that starting with version 3 we are using Go modules for versioning instead of gopkg.in as before.

Version 1 (on the v1 branch) is frozen and not supported anymore.

Supported algorithms

See below for a table of supported algorithms. Algorithm identifiers match the names in the JSON Web Algorithms standard where possible. The Godoc reference has a list of constants.

Key encryptionAlgorithm identifier(s)
RSA-PKCS#1v1.5RSA1_5
RSA-OAEPRSA-OAEP, RSA-OAEP-256
AES key wrapA128KW, A192KW, A256KW
AES-GCM key wrapA128GCMKW, A192GCMKW, A256GCMKW
ECDH-ES + AES key wrapECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW
ECDH-ES (direct)ECDH-ES1
Direct encryptiondir1

1. Not supported in multi-recipient mode

Signing / MACAlgorithm identifier(s)
RSASSA-PKCS#1v1.5RS256, RS384, RS512
RSASSA-PSSPS256, PS384, PS512
HMACHS256, HS384, HS512
ECDSAES256, ES384, ES512
Ed25519EdDSA2

2. Only available in version 2 of the package

Content encryptionAlgorithm identifier(s)
AES-CBC+HMACA128CBC-HS256, A192CBC-HS384, A256CBC-HS512
AES-GCMA128GCM, A192GCM, A256GCM
CompressionAlgorithm identifiers(s)
DEFLATE (RFC 1951)DEF

Supported key types

See below for a table of supported key types. These are understood by the library, and can be passed to corresponding functions such as NewEncrypter or NewSigner. Each of these keys can also be wrapped in a JWK if desired, which allows attaching a key id.

Algorithm(s)Corresponding types
RSA*rsa.PublicKey, *rsa.PrivateKey
ECDH, ECDSA*ecdsa.PublicKey, *ecdsa.PrivateKey
EdDSA1ed25519.PublicKey, ed25519.PrivateKey
AES, HMAC[]byte

1. Only available in version 2 or later of the package

Examples

Examples can be found in the Godoc reference for this package. The jose-util subdirectory also contains a small command-line utility which might be useful as an example as well.

Author: Square
Source Code: https://github.com/square/go-jose 
License: 

#golang #go 

What is GEEK

Buddha Community

Go-jose: An Implementation Of JOSE Standards (JWE, JWS, JWT) in Go

Go-jose: An Implementation Of JOSE Standards (JWE, JWS, JWT) in Go

Go JOSE

Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSON Web Encryption, JSON Web Signature, and JSON Web Token standards.

Disclaimer: This library contains encryption software that is subject to the U.S. Export Administration Regulations. You may not export, re-export, transfer or download this code or any part of it in violation of any United States law, directive or regulation. In particular this software may not be exported or re-exported in any form or on any media to Iran, North Sudan, Syria, Cuba, or North Korea, or to denied persons or entities mentioned on any US maintained blocked list.

Overview

The implementation follows the JSON Web Encryption (RFC 7516), JSON Web Signature (RFC 7515), and JSON Web Token (RFC 7519) specifications. Tables of supported algorithms are shown below. The library supports both the compact and JWS/JWE JSON Serialization formats, and has optional support for multiple recipients. It also comes with a small command-line utility (jose-util) for dealing with JOSE messages in a shell.

Note: We use a forked version of the encoding/json package from the Go standard library which uses case-sensitive matching for member names (instead of case-insensitive matching). This is to avoid differences in interpretation of messages between go-jose and libraries in other languages.

Versions

Version 2 (branch, doc) is the current stable version:

import "gopkg.in/square/go-jose.v2"

Version 3 (branch, doc) is the under development/unstable version (not released yet):

import "github.com/go-jose/go-jose/v3"

All new feature development takes place on the master branch, which we are preparing to release as version 3 when it's ready. Version 2 will continue to receive critical bug and security fixes. Note that starting with version 3 we are using Go modules for versioning instead of gopkg.in as before.

Version 1 (on the v1 branch) is frozen and not supported anymore.

Supported algorithms

See below for a table of supported algorithms. Algorithm identifiers match the names in the JSON Web Algorithms standard where possible. The Godoc reference has a list of constants.

Key encryptionAlgorithm identifier(s)
RSA-PKCS#1v1.5RSA1_5
RSA-OAEPRSA-OAEP, RSA-OAEP-256
AES key wrapA128KW, A192KW, A256KW
AES-GCM key wrapA128GCMKW, A192GCMKW, A256GCMKW
ECDH-ES + AES key wrapECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW
ECDH-ES (direct)ECDH-ES1
Direct encryptiondir1

1. Not supported in multi-recipient mode

Signing / MACAlgorithm identifier(s)
RSASSA-PKCS#1v1.5RS256, RS384, RS512
RSASSA-PSSPS256, PS384, PS512
HMACHS256, HS384, HS512
ECDSAES256, ES384, ES512
Ed25519EdDSA2

2. Only available in version 2 of the package

Content encryptionAlgorithm identifier(s)
AES-CBC+HMACA128CBC-HS256, A192CBC-HS384, A256CBC-HS512
AES-GCMA128GCM, A192GCM, A256GCM
CompressionAlgorithm identifiers(s)
DEFLATE (RFC 1951)DEF

Supported key types

See below for a table of supported key types. These are understood by the library, and can be passed to corresponding functions such as NewEncrypter or NewSigner. Each of these keys can also be wrapped in a JWK if desired, which allows attaching a key id.

Algorithm(s)Corresponding types
RSA*rsa.PublicKey, *rsa.PrivateKey
ECDH, ECDSA*ecdsa.PublicKey, *ecdsa.PrivateKey
EdDSA1ed25519.PublicKey, ed25519.PrivateKey
AES, HMAC[]byte

1. Only available in version 2 or later of the package

Examples

Examples can be found in the Godoc reference for this package. The jose-util subdirectory also contains a small command-line utility which might be useful as an example as well.

Author: Square
Source Code: https://github.com/square/go-jose 
License: 

#golang #go 

Fannie  Zemlak

Fannie Zemlak

1599854400

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.

#go #golang #go 1.15 #go features #go improvement #go package #go new features

Elian  Harber

Elian Harber

1667472242

JWT-go: A Go Implementation Of JSON Web Tokens

jwt-go

A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens.

Starting with v4.0.0 this project adds Go module support, but maintains backwards compatibility with older v3.x.y tags and upstream github.com/dgrijalva/jwt-go. See the MIGRATION_GUIDE.md for more information.

After the original author of the library suggested migrating the maintenance of jwt-go, a dedicated team of open source maintainers decided to clone the existing library into this repository. See dgrijalva/jwt-go#462 for a detailed discussion on this topic.

SECURITY NOTICE: Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue dgrijalva/jwt-go#216 for more detail.

SECURITY NOTICE: It's important that you validate the alg presented is what you expect. This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.

Supported Go versions

Our support of Go versions is aligned with Go's version release policy. So we will support a major version of Go until there are two newer major releases. We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities which will not be fixed.

What the heck is a JWT?

JWT.io has a great introduction to JSON Web Tokens.

In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for Bearer tokens in Oauth 2. A token is made of three parts, separated by .'s. The first two parts are JSON objects, that have been base64url encoded. The last part is the signature, encoded the same way.

The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.

The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to RFC 7519 for information about reserved keys and the proper way to add your own.

What's in the box?

This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.

Installation Guidelines

  1. To install the jwt package, you first need to have Go installed, then you can use the command below to add jwt-go as a dependency in your Go program.
go get -u github.com/golang-jwt/jwt/v4
  1. Import it in your code:
import "github.com/golang-jwt/jwt/v4"

Examples

See the project documentation for examples of usage:

Extensions

This library publishes all the necessary components for adding your own signing methods or key functions. Simply implement the SigningMethod interface and register a factory method using RegisterSigningMethod or provide a jwt.Keyfunc.

A common use case would be integrating with different 3rd party signature providers, like key management services from various cloud providers or Hardware Security Modules (HSMs) or to implement additional standards.

ExtensionPurposeRepo
GCPIntegrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS)https://github.com/someone1/gcp-jwt-go
AWSIntegrates with AWS Key Management Service, KMShttps://github.com/matelang/jwt-go-aws-kms
JWKSProvides support for JWKS (RFC 7517) as a jwt.Keyfunchttps://github.com/MicahParks/keyfunc

Disclaimer: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers

Compliance

This library was last reviewed to comply with RFC 7519 dated May 2015 with a few notable differences:

  • In order to protect against accidental use of Unsecured JWTs, tokens using alg=none will only be accepted if the constant jwt.UnsafeAllowNoneSignatureType is provided as the key.

Project Status & Versioning

This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).

This project uses Semantic Versioning 2.0.0. Accepted pull requests will land on main. Periodically, versions will be tagged from main. You can find all the releases on the project releases page.

BREAKING CHANGES:* A full list of breaking changes is available in VERSION_HISTORY.md. See MIGRATION_GUIDE.md for more information on updating your code.

Usage Tips

Signing vs Encryption

A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:

  • The author of the token was in the possession of the signing secret
  • The data has not been modified since it was signed

It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, JWE, that provides this functionality. The companion project https://github.com/golang-jwt/jwe aims at a (very) experimental implementation of the JWE standard.

Choosing a Signing Method

There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.

Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any []byte can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.

Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.

Signing Methods and Key Types

Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:

  • The HMAC signing method (HS256,HS384,HS512) expect []byte values for signing and validation
  • The RSA signing method (RS256,RS384,RS512) expect *rsa.PrivateKey for signing and *rsa.PublicKey for validation
  • The ECDSA signing method (ES256,ES384,ES512) expect *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for validation
  • The EdDSA signing method (Ed25519) expect ed25519.PrivateKey for signing and ed25519.PublicKey for validation

JWT and OAuth

It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.

Without going too far down the rabbit hole, here's a description of the interaction of these technologies:

  • OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
  • OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that should only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
  • Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.

Troubleshooting

This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types.

More

Documentation can be found on pkg.go.dev.

The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.

golang-jwt incorporates a modified version of the JWT logo, which is distributed under the terms of the MIT License.

Download Details:

Author: Golang-jwt
Source Code: https://github.com/golang-jwt/jwt 
License: MIT license

#go #golang #auth #jwt 

顾 静

顾 静

1661099400

Go 中 JWT 身份验证指南

JSON Web 令牌 (JWT) 是处理在线身份验证的流行方法,您可以使用任何服务器端编程语言实现 JWT 身份验证。

对于一般的 JWT 阅读背景,我建议通过这些文章了解更多关于 JWT、最佳实践以及使用 JWT 保护 RESTful API 的信息。

本文旨在帮助您开始使用该golang-jwt包在您的 Go Web 应用程序中实现 JWT 身份验证。

golang-jwt 由于其特性和易用性,该包是在 Go 中实现 JWT 最流行的包。该golang-jwt包提供了生成和验证 JWT 的功能。

先决条件

您需要满足这些基本要求才能充分利用本教程。

  • 在您的机器上安装 Go 1.16 或更高版本(出于安全原因)
  • 使用 Go 或任何其他语言构建 Web 应用程序的经验(可选)

Golang-JWT 包入门

设置好 Go 工作区并初始化 Go 模块文件go.mod后,在终端上的工作区目录中运行以下命令以安装golang-jwt包:

go get github.com/golang-jwt/jwt

安装后golang-jwt,创建一个 Go 文件并导入这些包和模块。

import (
   "log"
    "encoding/json"
   "github.com/golang-jwt/jwt"
   "net/http"
   "time"
)

您将在本教程中使用这些包来记录错误、设置服务器和设置令牌过期时间。

在 Go 中设置 Web 服务器

让我们从创建一个简单的 Web 服务器开始,该服务器的端点将由 JWT 保护。

func main() {
   http.HandleFunc("/home", handlePage)
   err := http.ListenAndServe(":8080", nil)
   if err != nil {
      log.Println("There was an error listening on port :8080", err)
   }

}

主函数使用handlePage您将设置的处理程序函数设置主端点。该handlePage函数将使用 JWT 保护页面。服务器设置为侦听端口:8080,但您可以使用您选择的任何端口。

如果在请求正文编码后请求被授权,则处理函数将返回结构的编码 JSON 作为对客户端的响应handlePageMessage

type Message struct {
        Status string `json:"status"`
        Info   string `json:"info"`
}

func handlePage(writer http.ResponseWriter, request *http.Request) {
        writer.Header().Set("Content-Type", "application/json")
        var message Message
        err := json.NewDecoder(request.Body).Decode(&message)
        if err != nil {
                return
        }
        err = json.NewEncoder(writer).Encode(message)
        if err != nil {
                return
        }
}

此时,该handlePage功能尚未经过身份验证,向页面发出请求将可以自由工作。您将在本教程的后面部分学习如何向处理程序函数添加身份验证。

API网络页面

使用包生成 JWT 进行身份验证Golang-JWT

您将需要一个密钥来使用该golang-jwt包生成 JWT 令牌。这是本教程的示例私钥;但是,您应该为您的密钥使用加密安全字符串,并从环境变量文件 (.env) 中加载它。

查看这篇文章,了解如何在 Go 应用程序中使用环境变量。

var sampleSecretKey = []byte("SecretYouShouldHide")

请注意,任何拥有您用于 JWT 的密钥的人都可以对您的应用程序的用户进行身份验证。在这种sampleSecretKey情况下,变量保存私钥。

这是一个生成 JWT 令牌的函数。该函数应返回一个字符串和一个错误。如果生成 JWT 时出错,该函数将返回一个空字符串和错误。如果没有错误,该函数将返回 JWT 字符串和nil类型。

func generateJWT() (string, error) {

}

New您可以使用JWT 包的方法创建新令牌。该New方法采用签名方法(JWT 的加密算法)并返回 JWT 令牌。

token := jwt.New(jwt.SigningMethodEdDSA)

如果要修改JWT,可以使用Claimstoken的方法。

claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute)
claims["authorized"] = true
claims["user"] = "username"

在这种情况下,您将使用time模块以及用户名和授权状态为 JWT 设置过期时间,即十分钟。在尝试验证 JWT 时,您将能够检索声明。

生成 JWT 的最后一部分是使用您的密钥对字符串进行签名。您可以使用令牌的SignedString方法对令牌字符串进行签名。该SignedString方法采用密钥并返回签名的令牌字符串。

tokenString, err := token.SignedString(sampleSecretKey)
if err != nil {
    return "", err
 }

 return tokenString, nil

如果签署令牌时出现错误,您可以返回空字符串和错误。
不像cookies,你不需要存储JWT;您所需要的只是您的签名密钥来验证令牌。

验证 JWT 令牌

验证 JWT 的传统方法使用中间件(处理函数接受其他处理函数进行操作)。下面介绍如何使用中间件来验证请求是否被授权。

func verifyJWT(endpointHandler func(writer http.ResponseWriter, request *http.Request)) http.HandlerFunc {

}

verifyJWT函数是一个中间件,它接收您要验证的请求的处理函数。处理函数使用请求标头中的令牌参数来验证请求并根据状态进行响应。

 return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {

})

如果请求被授权,该verifyJWT函数返回作为参数传入的处理函数。

验证 JWT 的第一步是检查请求标头中的令牌。

if request.Header["Token"] != nil {

}

如果有令牌,您可以继续验证令牌并验证声明。

您必须解析令牌,并且可以使用包的Parse方法解析令牌jwt。该parse方法接受令牌和 JWT 装饰器函数并返回接口和错误。

您需要使用生成令牌时用于签名令牌的相同签名方法,以使用令牌的Method方法验证签名。在这种情况下,签名方法是ECDSA方法。

token, err := jwt.Parse(request.Header\["Token"\][0], func(token *jwt.Token) (interface{}, error) {
            _, ok := token.Method.(*jwt.SigningMethodECDSA)
            if !ok {
               writer.WriteHeader(http.StatusUnauthorized)
               _, err := writer.Write([]byte("You're Unauthorized!"))
               if err != nil {
                  return nil, err

               }
            }
            return "", nil

         })

如果签名验证失败(函数返回!ok),您可以StatusUnauthorized向客户端返回一个标头。

if err != nil {
               writer.WriteHeader(http.StatusUnauthorized)
               _, err2 := writer.Write([]byte("You're Unauthorized due to error parsing the JWT"))
              if err2 != nil {
                      return
                }
}

在上面的代码中,解析令牌时出错。因此,用户是未经授权的,您可以编写消息并返回未经授权的状态。

您可以使用令牌的Valid方法来验证令牌。

if token.Valid {
                      endpointHandler(writer, request)
                        } else {
                                writer.WriteHeader(http.StatusUnauthorized)
                                _, err := writer.Write([]byte("You're Unauthorized due to invalid token"))
                                if err != nil {
                                        return
                                }
}

如果令牌有效,您可以将端点处理程序与处理函数的writerrequest参数一起传递给中间件函数以返回端点。

以下是else客户端请求的标头中没有令牌的情况的语句:

else {
          writer.WriteHeader(http.StatusUnauthorized)
          _, err := writer.Write([]byte("You're Unauthorized due to No token in the header"))
           if err != nil {
               return
           }
}

由于您使用的是中间件,因此路由声明中的处理函数将是verifyJWT中间件,其中路由的处理函数作为参数。

http.HandleFunc("/home", verifyJWT(handlePage))

将验证功能添加到路由后,端点就会通过身份验证。

端点认证

在客户端,客户端必须提供已发布的令牌。这是一个使用该generateJWT函数在请求中添加令牌的函数。

func authPage(writer http.ResponseWriter, ) {
        token, err := generateJWT()
        if err != nil {
                        return
        } 
        client := &http.Client{}
        request, _ := http.NewRequest("POST", "<http://localhost:8080/>", nil)
        request.Header.Set("Token", token)
        _, _ = client.Do(request)

}

authPage函数中,token变量保存来自函数的标记generateJWT。使用Client对包类型的引用http,您可以创建一个新客户端并向端点发出请求。request变量是请求实例,并且 - 使用请求实例的方法Setheader方法 - 您可以在请求标头中设置令牌,如上所示。

您还可以选择将令牌设置为 cookie,并在客户端向经过身份验证的端点发出请求时检索它以进行验证。

从 JWT 令牌中提取声明

在生成 JWT 时,您可以选择在令牌中嵌入信息。在generateJWT函数中,您将username变量添加到claims地图中。

以下是提取声明的方法,以username声明为例。验证令牌签名时,您可以使用中间件或将功能添加到验证函数中。

func extractClaims(_ http.ResponseWriter, request *http.Request) (string, error) {
        if request.Header["Token"] != nil {
                tokenString := request.Header\["Token"\][0]
                token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

          if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
                return nil, fmt.Errorf("there's an error with the signing method")
          }
                return sampleSecretKey, nil

            })

            if err != nil {
                        return "Error Parsing Token: ", err
                }
}

extractClaims函数中,过程与verifyJWT函数相同;您从标头中检索了令牌,解析了令牌并验证了签名。

claims, ok := token.Claims.(jwt.MapClaims)
          if ok && token.Valid {
                username := claims["username"].(string)
                return username, nil
          }

        }
        return "unable to extract claims", nil

在验证令牌时,您可以使用该Claims方法检索声明,并使用声明映射来检索 JWT 中的数据,如上所示。

结论

本教程教您如何使用 JWT 身份验证通过使用 JSON Web Tokens 包在 Go 中对 API 和网页端点进行身份验证golang-jwt。您可以在本教程中以Github Gist的形式找到完整的代码。

请记住为您的密钥使用环境变量,并且不要在 JWT 中隐藏敏感数据。LogRocket 博客上有许多 JWT 教程,您可以查看这些教程以开始使用您感兴趣的语言或框架!

来源:https ://blog.logrocket.com/jwt-authentication-go/

#go #jwt 

A Guide to JWT Authentication in Go

JSON Web Tokens (JWTs) are a popular method for dealing with online authentication, and you can implement JWT authentication in any server-side programming language.

For background reading JWTs in general, I recommend learning more about JWTs, best practices, and securing RESTful APIs with JWTs with these articles.

This article is aimed at helping you get started with implementing JWT authentication in your Go web applications using the golang-jwt package.

The golang-jwt package is the most popular package for implementing JWTs in Go, owing to its features and ease of use. The golang-jwt package provides functionality for generating and validating JWTs.

See more at: https://blog.logrocket.com/jwt-authentication-go/

#go #jwt