jwtauth

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

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

Go to latest
Published: Sep 13, 2016 License: MIT Imports: 7 Imported by: 0

README

jwtauth - JWT middleware for Go 1.7+ HTTP services

The jwtauth middleware is a simple way to verify a JWT token from a request and send the result down the request context (context.Context).

NOTE: jwtauth requires v2.7.0 of the github.com/dgrijalva/jwt-go dependency. Please make sure to vendor the correct version into your project. There is a PR https://github.com/goware/jwtauth/pull/8 to support v3.0.0, and it's quite close, but it needs another review after recent updates to jwt-go.

This package uses the new context package in Go 1.7 also used by net/http to manage request contexts.

In a complete JWT-authentication sequence, you'll first capture the token from a request, decode it, verify and then validate that is correctly signed and hasn't expired - the jwtauth.Verifier middleware handler takes care of all of that. Next, it's up to an authentication handler to determine what to do with a valid or invalid token. The jwtauth.Authenticator is a provided authentication middleware to enforce access following the Verifier. The Authenticator sends a 401 Unauthorized response for all unverified tokens and passes the good ones through. You can also copy the Authenticator and customize it to handle invalid tokens to better fit your flow.

The Verifier middleware will look for a JWT token from:

  1. 'jwt' URI query parameter
  2. 'Authorization: BEARER T' request header
  3. Cookie 'jwt' value
  4. (optional), use jwtauth.Verify("state") for additional query parameter aliases

The verification processes finishes here and sets the token and a error in the request context and calls the next handler.

Make sure to have your own handler following the Validator that will check the value of the "jwt" and "jwt.err" in the context and respond to the client accordingly. A generic Authenticator middleware is provided by this package, that will return a 401 message for all unverified tokens, see jwtauth.Authenticator.

Usage

See the full example.

package main

import (
	"fmt"
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/goware/jwtauth"
	"github.com/pressly/chi"
	"golang.org/x/net/context"
)

var TokenAuth *jwtauth.JwtAuth

func init() {
	TokenAuth = jwtauth.New("HS256", []byte("secret"), nil)
}

func router() http.Handler {
	r := chi.NewRouter()

	// Protected routes
	r.Group(func(r chi.Router) {
		// Seek, verify and validate JWT tokens
		r.Use(TokenAuth.Verifier)

		// Handle valid / invalid tokens. In this example, we use
		// the provided authenticator middleware, but you can write your
		// own very easily, look at the Authenticator method in jwtauth.go
		// and tweak it, its not scary.
		r.Use(jwtauth.Authenticator)

		r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()
			token := ctx.Value("jwt").(*jwt.Token)
			claims := token.Claims
			w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
		})
	})

	// Public routes
	r.Group(func(r chi.Router) {
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("welcome anonymous"))
		})
	})

	return r
}

LICENSE

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnauthorized = errors.New("jwtauth: unauthorized token")
	ErrExpired      = errors.New("jwtauth: expired token")
)

Functions

func Authenticator

func Authenticator(next http.Handler) http.Handler

Authenticator is a default authentication middleware to enforce access following the Verifier middleware. The Authenticator sends a 401 Unauthorized response for all unverified tokens and passes the good ones through. It's just fine until you decide to write something similar and customize your client response.

func EpochNow

func EpochNow() int64

Helper function that returns the NumericDate time value used by the spec

func ExpireIn

func ExpireIn(tm time.Duration) int64

Helper function to return calculated time in the future for "exp" claim.

Types

type Claims

type Claims map[string]interface{}

Claims is a convenience type to manage a JWT claims hash.

func (Claims) Get

func (c Claims) Get(k string) (interface{}, bool)

func (Claims) Set

func (c Claims) Set(k string, v interface{}) Claims

func (Claims) SetExpiry

func (c Claims) SetExpiry(tm time.Time) Claims

Set expiry ("exp") in the claims and return itself so it can be chained

func (Claims) SetExpiryIn

func (c Claims) SetExpiryIn(tm time.Duration) Claims

Set expiry ("exp") in the claims to some duration from the present time and return itself so it can be chained

func (Claims) SetIssuedAt

func (c Claims) SetIssuedAt(tm time.Time) Claims

Set issued at ("iat") to specified time in the claims

func (Claims) SetIssuedNow

func (c Claims) SetIssuedNow() Claims

Set issued at ("iat") to present time in the claims

type JwtAuth

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

func New

func New(alg string, signKey []byte, verifyKey []byte) *JwtAuth

New creates a JwtAuth authenticator instance that provides middleware handlers and encoding/decoding functions for JWT signing.

func NewWithParser

func NewWithParser(alg string, parser *jwt.Parser, signKey []byte, verifyKey []byte) *JwtAuth

NewWithParser is the same as New, except it supports custom parser settings introduced in ver. 2.4.0 of jwt-go

func (*JwtAuth) Decode

func (ja *JwtAuth) Decode(tokenString string) (t *jwt.Token, err error)

func (*JwtAuth) Encode

func (ja *JwtAuth) Encode(claims Claims) (t *jwt.Token, tokenString string, err error)

func (*JwtAuth) IsExpired

func (ja *JwtAuth) IsExpired(t *jwt.Token) bool

func (*JwtAuth) SetContext

func (ja *JwtAuth) SetContext(ctx context.Context, t *jwt.Token, err error) context.Context

func (*JwtAuth) Verifier

func (ja *JwtAuth) Verifier(next http.Handler) http.Handler

Verifier middleware will verify a JWT passed by a client request. The Verifier will look for a JWT token from: 1. 'jwt' URI query parameter 2. 'Authorization: BEARER T' request header 3. Cookie 'jwt' value

The verification processes finishes here and sets the token and a error in the request context and calls the next handler.

Make sure to have your own handler following the Validator that will check the value of the "jwt" and "jwt.err" in the context and respond to the client accordingly. A generic Authenticator middleware is provided by this package, that will return a 401 message for all unverified tokens, see jwtauth.Authenticator.

func (*JwtAuth) Verify

func (ja *JwtAuth) Verify(paramAliases ...string) func(http.Handler) http.Handler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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