Skip to content

Commit

Permalink
Merge 4fa7f8a into fbf5fc1
Browse files Browse the repository at this point in the history
  • Loading branch information
ckaznocha committed Apr 22, 2017
2 parents fbf5fc1 + 4fa7f8a commit 70342ed
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 25 deletions.
21 changes: 16 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![GoDoc](https://godoc.org/github.com/ckaznocha/go-JWTBearerware?status.svg)](https://godoc.org/github.com/ckaznocha/go-JWTBearerware)
[![Go Report Card](https://goreportcard.com/badge/ckaznocha/go-JWTBearerware)](https://goreportcard.com/report/ckaznocha/go-JWTBearerware)

A Go library to make using [JSON Web Tokens](https://jwt.io/) in gRPC and HTTP requests more convenient. Middleware functions and examples for some popular routers are in the `midleware` directory.
Package bearerware provides a library and middleware to make using [JSON Web Tokens](https://jwt.io/) 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](https://github.com/auth0/go-jwt-middleware).

Expand All @@ -27,7 +27,7 @@ func JWTFromContext(
signingMethod jwt.SigningMethod,
) (*jwt.Token, error)
```
JWTFromContext extracts a valid JWT from a context.Contexts or returns and error
JWTFromContext **deprecated** use `JWTFromIncomingContext`

#### func JWTFromHeader

Expand All @@ -40,13 +40,24 @@ func JWTFromHeader(
```
JWTFromHeader extracts a valid JWT from an http.Request or returns and error

#### func JWTFromIncomingContext

```go
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

```go
func NewJWTAccessFromJWT(jsonKey string) (credentials.Credentials, error)
func NewJWTAccessFromJWT(jsonKey string) (credentials.PerRPCCredentials, error)
```
NewJWTAccessFromJWT creates a JWT credentials.Credentials which can be used in
gRPC requests.
NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials for use in gRPC requests.

#### func WriteAuthError

Expand Down
6 changes: 3 additions & 3 deletions bearerware.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// Package bearerware provides a library and middleware for using JSON Web
// Tokens in gRPC and HTTP projects.
package bearerware

import (
Expand All @@ -24,7 +22,9 @@ const (

var (
errRestricted = errors.New("Bearer realm=Restricted")
errBearerFormat = errors.New("Authorization header format must be Bearer {token}")
errBearerFormat = errors.New(
"Authorization header format must be Bearer {token}",
)
errTokenInvalid = errors.New("Token is invalid")
)

Expand Down
9 changes: 9 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
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.
*/
package bearerware
19 changes: 16 additions & 3 deletions example_gRPC_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bearerware_test
import (
"crypto/tls"
"fmt"
"log"
"net"
"time"

Expand Down Expand Up @@ -47,7 +48,11 @@ func (s *server) SayHello(
return nil, err
}
return &pb.HelloReply{
Message: fmt.Sprintf("Hello %s! Token signed using %s", in.Name, token.Method.Alg()),
Message: fmt.Sprintf(
"Hello %s! Token signed using %s",
in.Name,
token.Method.Alg(),
),
}, nil
}

Expand All @@ -67,7 +72,11 @@ func Example_gRPC() {
//Start the server
s := grpc.NewServer(opts...)
pb.RegisterGreeterServer(s, &server{})
go s.Serve(lis)
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
Expand All @@ -89,7 +98,11 @@ func Example_gRPC() {
if err != nil {
panic(fmt.Sprintf("did not connect: %v", err))
}
defer conn.Close()
defer func() {
if err := conn.Close(); err != nil {
log.Print(err)
}
}()
c := pb.NewGreeterClient(conn)

// Contact the server and print out its response.
Expand Down
29 changes: 23 additions & 6 deletions gRPC.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,19 @@ type jwtAccess struct {
}

/*
NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials which can be used
in gRPC requests.
NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials for use in gRPC
requests.
*/
func NewJWTAccessFromJWT(jsonKey string) (credentials.PerRPCCredentials, error) {
func NewJWTAccessFromJWT(
jsonKey string,
) (credentials.PerRPCCredentials, error) {
return jwtAccess{jsonKey}, nil
}

func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
func (j jwtAccess) GetRequestMetadata(
ctx context.Context,
uri ...string,
) (map[string]string, error) {
return map[string]string{
authHeader: fmt.Sprintf("%s%s", strings.Title(bearer), j.jsonKey),
}, nil
Expand All @@ -33,14 +38,26 @@ func (j jwtAccess) RequireTransportSecurity() bool {
}

/*
JWTFromContext extracts a valid JWT from a context.Contexts or returns and error
JWTFromContext **deprecated** use `JWTFromIncomingContext`
*/
func JWTFromContext(
ctx context.Context,
keyFunc jwt.Keyfunc,
signingMethod jwt.SigningMethod,
) (*jwt.Token, error) {
md, ok := metadata.FromContext(ctx)
return JWTFromIncomingContext(ctx, keyFunc, signingMethod)
}

/*
JWTFromIncomingContext extracts a valid JWT from a context.Contexts or returns
and error
*/
func JWTFromIncomingContext(
ctx context.Context,
keyFunc jwt.Keyfunc,
signingMethod jwt.SigningMethod,
) (*jwt.Token, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errRestricted
}
Expand Down
6 changes: 3 additions & 3 deletions gRPC_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestJWTFromContext(t *testing.T) {
err error
}{
{
ctx: metadata.NewContext(
ctx: metadata.NewIncomingContext(
context.Background(),
metadata.New(map[string]string{authHeader: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJpYXQiOm51bGwsImV4cCI6bnVsbCwiYXVkIjoiIiwic3ViIjoiIn0.IlffGJz3IyFX1ADQ6-jOTQ_0D-K0kuKq5SpB_oirCrk"}),
),
Expand All @@ -66,15 +66,15 @@ func TestJWTFromContext(t *testing.T) {
err: errors.New("Bearer realm=Restricted"),
},
{
ctx: metadata.NewContext(
ctx: metadata.NewIncomingContext(
context.Background(),
metadata.New(map[string]string{}),
),
signingMethod: jwt.SigningMethodHS256,
err: errors.New("Bearer realm=Restricted"),
},
{
ctx: metadata.NewContext(
ctx: metadata.NewIncomingContext(
context.Background(),
metadata.New(map[string]string{authHeader: "Beare eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJpYXQiOm51bGwsImV4cCI6bnVsbCwiYXVkIjoiIiwic3ViIjoiIn0.IlffGJz3IyFX1ADQ6-jOTQ_0D-K0kuKq5SpB_oirCrk"}),
),
Expand Down
16 changes: 13 additions & 3 deletions middleware/httprouter/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bwhttprouter_test

import (
"fmt"
"log"
"net/http"

"github.com/ckaznocha/go-JWTBearerware/middleware/httprouter"
Expand All @@ -11,7 +12,11 @@ import (

func ExampleJWTHandler() {
var (
handler = func(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
handler = func(
w http.ResponseWriter,
req *http.Request,
_ httprouter.Params,
) {
token, ok := bwhttprouter.JWTContext.ReadJWT(req)
if !ok {
http.Error(
Expand All @@ -28,7 +33,12 @@ func ExampleJWTHandler() {

router = httprouter.New()
)
router.GET("/", bwhttprouter.JWTHandler(handler, jwtKeyFunc, jwt.SigningMethodHS256))
router.GET(
"/",
bwhttprouter.JWTHandler(handler, jwtKeyFunc, jwt.SigningMethodHS256),
)

http.ListenAndServe("localhost:8080", router)
if err := http.ListenAndServe("localhost:8080", router); err != nil {
log.Print(err)
}
}
10 changes: 8 additions & 2 deletions middleware/net_http/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bwhttp_test

import (
"fmt"
"log"
"net/http"

"github.com/ckaznocha/go-JWTBearerware/middleware/net_http"
Expand All @@ -27,7 +28,12 @@ func ExampleJWTHandler() {

mux = http.NewServeMux()
)
mux.HandleFunc("/", bwhttp.JWTHandler(handler, jwtKeyFunc, jwt.SigningMethodHS256))
mux.HandleFunc(
"/",
bwhttp.JWTHandler(handler, jwtKeyFunc, jwt.SigningMethodHS256),
)

http.ListenAndServe("localhost:8080", mux)
if err := http.ListenAndServe("localhost:8080", mux); err != nil {
log.Print(err)
}
}

0 comments on commit 70342ed

Please sign in to comment.