jwtmiddleware

package module
v2.0.0-...-3dee013 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2022 License: MIT Imports: 5 Imported by: 0

README

GO JWT 中间件

GoDoc License Release Codecov Tests Stars Contributors


Golang 中间件 用于检查和验证 JWTs.


大纲


安装

go get github.com/authok/go-jwt-middleware/v2

[table of contents]

使用

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."}
...

[table of contents]

[table of contents]

作者

Authok

[table of contents]

许可

本项目基于 MIT 许可. 参考 LICENSE.

[table of contents]

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrJWTMissing is returned when the JWT is missing.
	ErrJWTMissing = errors.New("jwt missing")

	// ErrJWTInvalid is returned when the JWT is invalid.
	ErrJWTInvalid = errors.New("jwt invalid")
)

Functions

func AuthHeaderTokenExtractor

func AuthHeaderTokenExtractor(r *http.Request) (string, error)

AuthHeaderTokenExtractor is a TokenExtractor that takes a request and extracts the token from the Authorization header.

func DefaultErrorHandler

func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error)

DefaultErrorHandler is the default error handler implementation for the JWTMiddleware. If an error handler is not provided via the WithErrorHandler option this will be used.

Types

type ContextKey

type ContextKey struct{}

ContextKey is the key used in the request context where the information from a validated JWT will be stored.

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)

ErrorHandler is a handler which is called when an error occurs in the JWTMiddleware. Among some general errors, this handler also determines the response of the JWTMiddleware when a token is not found or is invalid. The err can be checked to be ErrJWTMissing or ErrJWTInvalid for specific cases. The default handler will return a status code of 400 for ErrJWTMissing, 401 for ErrJWTInvalid, and 500 for all other errors. If you implement your own ErrorHandler you MUST take into consideration the error types as not properly responding to them or having a poorly implemented handler could result in the JWTMiddleware not functioning as intended.

type JWTMiddleware

type JWTMiddleware struct {
	// contains filtered or unexported fields
}

func New

func New(validateToken ValidateToken, opts ...Option) *JWTMiddleware

New constructs a new JWTMiddleware instance with the supplied options. It requires a ValidateToken function to be passed in, so it can properly validate tokens.

func (*JWTMiddleware) CheckJWT

func (m *JWTMiddleware) CheckJWT(next http.Handler) http.Handler

CheckJWT is the main JWTMiddleware function which performs the main logic. It is passed a http.Handler which will be called if the JWT passes validation.

type Option

type Option func(*JWTMiddleware)

Option is how options for the JWTMiddleware are set up.

func WithCredentialsOptional

func WithCredentialsOptional(value bool) Option

WithCredentialsOptional sets up if credentials are optional or not. If set to true then an empty token will be considered valid.

Default value: false.

func WithErrorHandler

func WithErrorHandler(h ErrorHandler) Option

WithErrorHandler sets the handler which is called when we encounter errors in the JWTMiddleware. See the ErrorHandler type for more information.

Default value: DefaultErrorHandler.

func WithTokenExtractor

func WithTokenExtractor(e TokenExtractor) Option

WithTokenExtractor sets up the function which extracts the JWT to be validated from the request.

Default value: AuthHeaderTokenExtractor.

func WithValidateOnOptions

func WithValidateOnOptions(value bool) Option

WithValidateOnOptions sets up if OPTIONS requests should have their JWT validated or not.

Default value: true.

type TokenExtractor

type TokenExtractor func(r *http.Request) (string, error)

TokenExtractor is a function that takes a request as input and returns either a token or an error. An error should only be returned if an attempt to specify a token was found, but the information was somehow incorrectly formed. In the case where a token is simply not present, this should not be treated as an error. An empty string should be returned in that case.

func CookieTokenExtractor

func CookieTokenExtractor(cookieName string) TokenExtractor

CookieTokenExtractor builds a TokenExtractor that takes a request and extracts the token from the cookie using the passed in cookieName.

func MultiTokenExtractor

func MultiTokenExtractor(extractors ...TokenExtractor) TokenExtractor

MultiTokenExtractor returns a TokenExtractor that runs multiple TokenExtractors and takes the one that does not return an empty token. If a TokenExtractor returns an error that error is immediately returned.

func ParameterTokenExtractor

func ParameterTokenExtractor(param string) TokenExtractor

ParameterTokenExtractor returns a TokenExtractor that extracts the token from the specified query string parameter.

type ValidateToken

type ValidateToken func(context.Context, string) (interface{}, error)

ValidateToken takes in a string JWT and makes sure it is valid and returns the valid token. If it is not valid it will return nil and an error message describing why validation failed. Inside ValidateToken things like key and alg checking can happen. In the default implementation we can add safe defaults for those.

Directories

Path Synopsis
examples
internal
Package validator contains an implementation of jwtmiddleware.ValidateToken using the Square go-jose package version 2.
Package validator contains an implementation of jwtmiddleware.ValidateToken using the Square go-jose package version 2.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL