jwt

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2018 License: MIT Imports: 10 Imported by: 0

README

package auth/jwt

package auth/jwt provides a set of interfaces for service authorization through JSON Web Tokens.

Usage

NewParser takes a key function and an expected signing method and returns an endpoint.Middleware. The middleware will parse a token passed into the context via the jwt.JWTTokenContextKey. If the token is valid, any claims will be added to the context via the jwt.JWTClaimsContextKey.

import (
	stdjwt "github.com/dgrijalva/jwt-go"

	"github.com/inturn/kit/auth/jwt"
	"github.com/inturn/kit/endpoint"
)

func main() {
	var exampleEndpoint endpoint.Endpoint
	{
		kf := func(token *stdjwt.Token) (interface{}, error) { return []byte("SigningString"), nil }
		exampleEndpoint = MakeExampleEndpoint(service)
		exampleEndpoint = jwt.NewParser(kf, stdjwt.SigningMethodHS256, jwt.StandardClaimsFactory)(exampleEndpoint)
	}
}

NewSigner takes a JWT key ID header, the signing key, signing method, and a claims object. It returns an endpoint.Middleware. The middleware will build the token string and add it to the context via the jwt.JWTTokenContextKey.

import (
	stdjwt "github.com/dgrijalva/jwt-go"

	"github.com/inturn/kit/auth/jwt"
	"github.com/inturn/kit/endpoint"
)

func main() {
	var exampleEndpoint endpoint.Endpoint
	{
		exampleEndpoint = grpctransport.NewClient(...).Endpoint()
		exampleEndpoint = jwt.NewSigner(
			"kid-header",
			[]byte("SigningString"),
			stdjwt.SigningMethodHS256,
			jwt.Claims{},
		)(exampleEndpoint)
	}
}

In order for the parser and the signer to work, the authorization headers need to be passed between the request and the context. HTTPToContext(), ContextToHTTP(), GRPCToContext(), and ContextToGRPC() are given as helpers to do this. These functions implement the correlating transport's RequestFunc interface and can be passed as ClientBefore or ServerBefore options.

Example of use in a client:

import (
	stdjwt "github.com/dgrijalva/jwt-go"

	grpctransport "github.com/inturn/kit/transport/grpc"
	"github.com/inturn/kit/auth/jwt"
	"github.com/inturn/kit/endpoint"
)

func main() {

	options := []httptransport.ClientOption{}
	var exampleEndpoint endpoint.Endpoint
	{
		exampleEndpoint = grpctransport.NewClient(..., grpctransport.ClientBefore(jwt.ContextToGRPC())).Endpoint()
		exampleEndpoint = jwt.NewSigner(
			"kid-header",
			[]byte("SigningString"),
			stdjwt.SigningMethodHS256,
			jwt.Claims{},
		)(exampleEndpoint)
	}
}

Example of use in a server:

import (
	"context"

	"github.com/inturn/kit/auth/jwt"
	"github.com/inturn/kit/log"
	grpctransport "github.com/inturn/kit/transport/grpc"
)

func MakeGRPCServer(ctx context.Context, endpoints Endpoints, logger log.Logger) pb.ExampleServer {
	options := []grpctransport.ServerOption{grpctransport.ServerErrorLogger(logger)}

	return &grpcServer{
		createUser: grpctransport.NewServer(
			ctx,
			endpoints.CreateUserEndpoint,
			DecodeGRPCCreateUserRequest,
			EncodeGRPCCreateUserResponse,
			append(options, grpctransport.ServerBefore(jwt.GRPCToContext()))...,
		),
		getUser: grpctransport.NewServer(
			ctx,
			endpoints.GetUserEndpoint,
			DecodeGRPCGetUserRequest,
			EncodeGRPCGetUserResponse,
			options...,
		),
	}
}

Documentation

Index

Constants

View Source
const (
	// JWTTokenContextKey holds the key used to store a JWT Token in the
	// context.
	JWTTokenContextKey contextKey = "JWTToken"

	// JWTClaimsContextKey holds the key used to store the JWT Claims in the
	// context.
	JWTClaimsContextKey contextKey = "JWTClaims"
)

Variables

View Source
var (
	// ErrTokenContextMissing denotes a token was not passed into the parsing
	// middleware's context.
	ErrTokenContextMissing = errors.New("token up for parsing was not passed through the context")

	// ErrTokenInvalid denotes a token was not able to be validated.
	ErrTokenInvalid = errors.New("JWT Token was invalid")

	// ErrTokenExpired denotes a token's expire header (exp) has since passed.
	ErrTokenExpired = errors.New("JWT Token is expired")

	// ErrTokenMalformed denotes a token was not formatted as a JWT token.
	ErrTokenMalformed = errors.New("JWT Token is malformed")

	// ErrTokenNotActive denotes a token's not before header (nbf) is in the
	// future.
	ErrTokenNotActive = errors.New("token is not valid yet")

	// ErrUnexpectedSigningMethod denotes a token was signed with an unexpected
	// signing method.
	ErrUnexpectedSigningMethod = errors.New("unexpected signing method")
)

Functions

func ContextToGRPC added in v0.6.0

func ContextToGRPC() grpc.ClientRequestFunc

ContextToGRPC moves a JWT from context to grpc metadata. Particularly useful for clients.

func ContextToHTTP added in v0.6.0

func ContextToHTTP() http.RequestFunc

ContextToHTTP moves a JWT from context to request header. Particularly useful for clients.

func GRPCToContext added in v0.6.0

func GRPCToContext() grpc.ServerRequestFunc

GRPCToContext moves a JWT from grpc metadata to context. Particularly userful for servers.

func HTTPToContext added in v0.6.0

func HTTPToContext() http.RequestFunc

HTTPToContext moves a JWT from request header to context. Particularly useful for servers.

func MapClaimsFactory added in v0.6.0

func MapClaimsFactory() jwt.Claims

MapClaimsFactory is a ClaimsFactory that returns an empty jwt.MapClaims.

func NewParser

func NewParser(keyFunc jwt.Keyfunc, method jwt.SigningMethod, newClaims ClaimsFactory) endpoint.Middleware

NewParser creates a new JWT token parsing middleware, specifying a jwt.Keyfunc interface, the signing method and the claims type to be used. NewParser adds the resulting claims to endpoint context or returns error on invalid token. Particularly useful for servers.

func NewSigner

func NewSigner(kid string, key []byte, method jwt.SigningMethod, claims jwt.Claims) endpoint.Middleware

NewSigner creates a new JWT token generating middleware, specifying key ID, signing string, signing method and the claims you would like it to contain. Tokens are signed with a Key ID header (kid) which is useful for determining the key to use for parsing. Particularly useful for clients.

func StandardClaimsFactory added in v0.6.0

func StandardClaimsFactory() jwt.Claims

StandardClaimsFactory is a ClaimsFactory that returns an empty jwt.StandardClaims.

Types

type ClaimsFactory added in v0.6.0

type ClaimsFactory func() jwt.Claims

ClaimsFactory is a factory for jwt.Claims. Useful in NewParser middleware.

Jump to

Keyboard shortcuts

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