modulepackage
2.0.0-20220530142741-3dee01339869
Repository: https://github.com/authok/go-jwt-middleware.git
Documentation: pkg.go.dev
# README
GO JWT 中间件
Golang 中间件 用于检查和验证 JWTs.
大纲
安装
go get github.com/authok/go-jwt-middleware/v2
使用
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/authok/go-jwt-middleware/v2"
"github.com/authok/go-jwt-middleware/v2/validator"
)
var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(jwtmiddleware.ContextKey{}).(*validator.ValidatedClaims)
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."}
...
作者
许可
本项目基于 MIT 许可. 参考 LICENSE.
# Functions
AuthHeaderTokenExtractor is a TokenExtractor that takes a request and extracts the token from the Authorization header.
CookieTokenExtractor builds a TokenExtractor that takes a request and extracts the token from the cookie using the passed in cookieName.
DefaultErrorHandler is the default error handler implementation for the JWTMiddleware.
MultiTokenExtractor returns a TokenExtractor that runs multiple TokenExtractors and takes the one that does not return an empty token.
New constructs a new JWTMiddleware instance with the supplied options.
ParameterTokenExtractor returns a TokenExtractor that extracts the token from the specified query string parameter.
WithCredentialsOptional sets up if credentials are optional or not.
WithErrorHandler sets the handler which is called when we encounter errors in the JWTMiddleware.
WithTokenExtractor sets up the function which extracts the JWT to be validated from the request.
WithValidateOnOptions sets up if OPTIONS requests should have their JWT validated or not.
# Variables
ErrJWTInvalid is returned when the JWT is invalid.
ErrJWTMissing is returned when the JWT is missing.
# Structs
ContextKey is the key used in the request context where the information from a validated JWT will be stored.
No description provided by the author
# Type aliases
ErrorHandler is a handler which is called when an error occurs in the JWTMiddleware.
Option is how options for the JWTMiddleware are set up.
TokenExtractor is a function that takes a request as input and returns either a token or an error.
ValidateToken takes in a string JWT and makes sure it is valid and returns the valid token.