go-jwt-middleware
A Middleware for Go Programming Language to check for JWTs on HTTP requests
Top Related Projects
Complete implementation of JWx (Javascript Object Signing and Encryption/JOSE) technologies for Go. #golang #jwt #jws #jwk #jwe
Quick Overview
go-jwt-middleware is a middleware for Go that provides JSON Web Token (JWT) authentication. It allows developers to easily integrate JWT-based authentication into their Go web applications, supporting various JWT signing algorithms and customizable validation options.
Pros
- Easy integration with popular Go web frameworks like Gin, Echo, and standard net/http
- Supports multiple JWT signing algorithms (HS256, RS256, etc.)
- Customizable token extraction methods (from headers, query parameters, or cookies)
- Flexible validation options, including custom claim validators
Cons
- Limited documentation and examples for advanced use cases
- Lack of built-in support for token refresh mechanisms
- No built-in rate limiting or brute force protection
- Relatively infrequent updates and maintenance
Code Examples
- Basic usage with net/http:
import (
"net/http"
"github.com/auth0/go-jwt-middleware/v2"
"github.com/auth0/go-jwt-middleware/v2/validator"
)
// Create a new validator
jwtValidator, err := validator.New(
func(ctx context.Context) (interface{}, error) {
return []byte("your-secret-key"), nil
},
validator.HS256,
"your-issuer",
[]string{"your-audience"},
)
// Create the middleware
jwtMiddleware := jwtmiddleware.New(jwtValidator.ValidateToken)
// Use the middleware in your handler
http.Handle("/api", jwtMiddleware.CheckJWT(http.HandlerFunc(apiHandler)))
- Custom claims validation:
customClaims := func(ctx context.Context, claims validator.Claims) error {
if claims.Subject == "" {
return errors.New("missing subject claim")
}
return nil
}
jwtValidator, err := validator.New(
// ... other options
validator.WithCustomClaims(customClaims),
)
- Token extraction from query parameter:
jwtMiddleware := jwtmiddleware.New(
jwtValidator.ValidateToken,
jwtmiddleware.WithTokenExtractor(jwtmiddleware.FromParameter("token")),
)
Getting Started
-
Install the package:
go get github.com/auth0/go-jwt-middleware/v2
-
Import the required packages:
import ( "github.com/auth0/go-jwt-middleware/v2" "github.com/auth0/go-jwt-middleware/v2/validator" )
-
Create a validator and middleware:
jwtValidator, _ := validator.New( func(ctx context.Context) (interface{}, error) { return []byte("your-secret-key"), nil }, validator.HS256, "your-issuer", []string{"your-audience"}, ) jwtMiddleware := jwtmiddleware.New(jwtValidator.ValidateToken)
-
Use the middleware in your HTTP handler:
http.Handle("/api", jwtMiddleware.CheckJWT(http.HandlerFunc(apiHandler)))
Competitor Comparisons
Complete implementation of JWx (Javascript Object Signing and Encryption/JOSE) technologies for Go. #golang #jwt #jws #jwk #jwe
Pros of jwx
- More comprehensive JWT library with support for various JWT-related operations
- Actively maintained with frequent updates and improvements
- Provides a wider range of functionality beyond middleware
Cons of jwx
- Steeper learning curve due to its broader feature set
- May be overkill for simple JWT authentication use cases
- Requires more setup and configuration compared to go-jwt-middleware
Code Comparison
go-jwt-middleware:
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("secret"), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
jwx:
key := []byte("secret")
token, err := jwt.Sign(jwt.New(), jwa.HS256, key)
parsed, err := jwt.Parse(bytes.NewReader(token), jwt.WithVerify(jwa.HS256, key))
Summary
jwx offers a more comprehensive JWT solution with broader functionality, while go-jwt-middleware focuses specifically on middleware for JWT authentication. jwx is better suited for projects requiring extensive JWT operations, whereas go-jwt-middleware provides a simpler, more straightforward approach for basic JWT authentication in web applications. The choice between the two depends on the specific requirements of your project and the level of JWT functionality needed.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð Documentation ⢠ð Getting Started ⢠ð¬ Feedback
Documentation
- Godoc - explore the go-jwt-middleware documentation.
- Docs site â explore our docs site and learn more about Auth0.
- Quickstart - our guide for adding go-jwt-middleware to your app.
Getting started
Requirements
This library follows the same support policy as Go. The last two major Go releases are actively supported and compatibility issues will be fixed. While you may find that older versions of Go may work, we will not actively test and fix compatibility issues with these versions.
- Go 1.23+
Installation
go get github.com/auth0/go-jwt-middleware/v2
Usage
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/auth0/go-jwt-middleware/v2"
"github.com/auth0/go-jwt-middleware/v2/validator"
jwtmiddleware "github.com/auth0/go-jwt-middleware/v2"
)
var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(jwtmiddleware.ContextKey{}).(*validator.ValidatedClaims)
if !ok {
http.Error(w, "failed to get validated claims", http.StatusInternalServerError)
return
}
payload, err := json.Marshal(claims)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(payload)
})
func main() {
keyFunc := func(ctx context.Context) (interface{}, error) {
// Our token must be signed using this data.
return []byte("secret"), nil
}
// Set up the validator.
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"https://<issuer-url>/",
[]string{"<audience>"},
)
if err != nil {
log.Fatalf("failed to set up the validator: %v", err)
}
// Set up the middleware.
middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
http.ListenAndServe("0.0.0.0:3000", middleware.CheckJWT(handler))
}
After running that code (go run main.go
) you can then curl the http server from another terminal:
$ curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJnby1qd3QtbWlkZGxld2FyZS1leGFtcGxlIiwiYXVkIjoiZ28tand0LW1pZGRsZXdhcmUtZXhhbXBsZSJ9.xcnkyPYu_b3qm2yeYuEgr5R5M5t4pN9s04U1ya53-KM" localhost:3000
That should give you the following response:
{
"CustomClaims": null,
"RegisteredClaims": {
"iss": "go-jwt-middleware-example",
"aud": "go-jwt-middleware-example",
"sub": "1234567890",
"iat": 1516239022
}
}
The JWT included in the Authorization header above is signed with secret
.
To test how the response would look like with an invalid token:
$ curl -v -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.yiDw9IDNCa1WXCoDfPR_g356vSsHBEerqh9IvnD49QE" localhost:3000
That should give you the following response:
...
< HTTP/1.1 401 Unauthorized
< Content-Type: application/json
{"message":"JWT is invalid."}
...
For more examples please check the examples folder.
Feedback
Contributing
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
Raise an issue
To provide feedback or report a bug, please raise an issue on our issue tracker.
Vulnerability Reporting
Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
Auth0 is an easy to implement, adaptable authentication and authorization platform.
To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.
Top Related Projects
Complete implementation of JWx (Javascript Object Signing and Encryption/JOSE) technologies for Go. #golang #jwt #jws #jwk #jwe
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot