bearerware

package module
v0.0.0-...-ba4d39b Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2017 License: MIT Imports: 9 Imported by: 0

README

bearerware

Build Status Coverage Status License GoDoc Go Report Card

Package bearerware provides a library and middleware to make using JSON Web Tokens in gRPC and HTTP requests more convenient. Middleware functions and examples for popular routers are in the midleware directory.

This project was inspire by auth0/go-jwt-middleware.

Requires go1.7 or newer.

For more info see the example files and the GoDoc page.

-- import "github.com/ckaznocha/go-JWTBearerware"

Usage

func JWTFromContext
func JWTFromContext(
	ctx context.Context,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromContext deprecated use JWTFromIncomingContext

func JWTFromHeader
func JWTFromHeader(
	r *http.Request,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromHeader extracts a valid JWT from an http.Request or returns and error

func JWTFromIncomingContext
func JWTFromIncomingContext(
	ctx context.Context,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromIncomingContext extracts a valid JWT from a context.Contexts or returns and error

func NewJWTAccessFromJWT
func NewJWTAccessFromJWT(jsonKey string) (credentials.PerRPCCredentials, error)

NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials for use in gRPC requests.

func WriteAuthError
func WriteAuthError(w http.ResponseWriter, err error)

WriteAuthError is a convenience function for setting the WWW-Authenticate header and sending an http.Error()

type JWTContexter
type JWTContexter interface {
	WriteJWT(*http.Request, *jwt.Token)
	ReadJWT(*http.Request) (*jwt.Token, bool)
	DeleteJWT(*http.Request)
}

JWTContexter provides and interface for safe access to a shared map to get a jwt for the current request scope when using net/http.

func NewJWTContext
func NewJWTContext() JWTContexter

NewJWTContext creates a new JWTContexter

Documentation

Overview

Package bearerware provides a library and middleware to make using JSON Web Tokens in gRPC and HTTP requests more convenient. Middleware functions and examples for popular routers are in the `midleware` directory.

This project was inspire by github.com/auth0/go-jwt-middleware.

Example (GRPC)
package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/ckaznocha/go-JWTBearerware"
	"github.com/dgrijalva/jwt-go"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
	certFile  = "./test_cert/server.pem"
	keyFile   = "./test_cert/server.key"
	host      = "127.0.0.1"
	port      = "50051"
	netString = "tcp"
)

var (
	jwtKey        = []byte("MySecret")
	signingMethod = jwt.SigningMethodHS256
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

func jwtKeyFunc(token *jwt.Token) (interface{}, error) {
	return jwtKey, nil
}

// SayHello implements helloworld.GreeterServer it requires a valid JWT
func (s *server) SayHello(
	ctx context.Context,
	in *pb.HelloRequest,
) (*pb.HelloReply, error) {
	//Validate and extract the JWT from the context using
	//bearerware.JWTFromContext
	token, err := bearerware.JWTFromContext(ctx, jwtKeyFunc, signingMethod)
	if err != nil {
		return nil, err
	}
	return &pb.HelloReply{
		Message: fmt.Sprintf(
			"Hello %s! Token signed using %s",
			in.Name,
			token.Method.Alg(),
		),
	}, nil
}

func main() {
	//The server needs to be started using TLS
	var (
		cert, _ = tls.LoadX509KeyPair(certFile, keyFile)
		opts    = []grpc.ServerOption{
			grpc.Creds(credentials.NewServerTLSFromCert(&cert)),
		}
	)
	lis, err := net.Listen(netString, net.JoinHostPort(host, port))
	if err != nil {
		panic(fmt.Sprintf("failed to listen: %v", err))
	}

	//Start the server
	s := grpc.NewServer(opts...)
	pb.RegisterGreeterServer(s, &server{})
	go func() {
		if err := s.Serve(lis); err != nil {
			log.Print(err)
		}
	}()
	defer s.Stop()

	// Set up a connection to the server using TLS and a JWT
	var (
		tlsCreds, _ = credentials.NewClientTLSFromFile(certFile, "localhost")
		//Create a JWT for  the example
		tokenString, _ = jwt.New(signingMethod).SignedString(jwtKey)
		jwtCreds, _    = bearerware.NewJWTAccessFromJWT(tokenString)
		dialOpts       = []grpc.DialOption{
			grpc.WithTransportCredentials(tlsCreds),
			//Pass our jwtCreds to grpc.WithPerRPCCredentials to have it
			//included in every request.
			grpc.WithPerRPCCredentials(jwtCreds),
			grpc.WithTimeout(5 * time.Second),
			grpc.WithBlock(),
		}
	)
	conn, err := grpc.Dial(net.JoinHostPort(host, port), dialOpts...)
	if err != nil {
		panic(fmt.Sprintf("did not connect: %v", err))
	}
	defer func() {
		if err := conn.Close(); err != nil {
			log.Print(err)
		}
	}()
	c := pb.NewGreeterClient(conn)

	// Contact the server and print out its response.
	// Our JWT is included in every request; no extra steps needed.
	r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: "World"})
	if err != nil {
		panic(fmt.Sprintf("could not greet: %v", err))
	}
	fmt.Printf("Greeting: %s", r.Message)
}
Output:

Greeting: Hello World! Token signed using HS256

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func JWTFromContext

func JWTFromContext(
	ctx context.Context,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromContext **deprecated** use `JWTFromIncomingContext`

func JWTFromHeader

func JWTFromHeader(
	r *http.Request,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromHeader extracts a valid JWT from an http.Request or returns and error

func JWTFromIncomingContext

func JWTFromIncomingContext(
	ctx context.Context,
	keyFunc jwt.Keyfunc,
	signingMethod jwt.SigningMethod,
) (*jwt.Token, error)

JWTFromIncomingContext extracts a valid JWT from a context.Contexts or returns and error

func NewJWTAccessFromJWT

func NewJWTAccessFromJWT(
	jsonKey string,
) (credentials.PerRPCCredentials, error)

NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials for use in gRPC requests.

func WriteAuthError

func WriteAuthError(w http.ResponseWriter, err error)

WriteAuthError is a convenience function for setting the WWW-Authenticate header and sending an http.Error()

Types

type JWTContexter

type JWTContexter interface {
	WriteJWT(*http.Request, *jwt.Token)
	ReadJWT(*http.Request) (*jwt.Token, bool)
	DeleteJWT(*http.Request)
}

JWTContexter provides and interface for safe access to a shared map to get a jwt for the current request scope when using net/http.

func NewJWTContext

func NewJWTContext() JWTContexter

NewJWTContext creates a new JWTContexter

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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