jaywt

package module
v0.0.0-...-326c75d Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2017 License: MIT Imports: 5 Imported by: 0

README

JayWT

godoc Build Status codecov

A utility package that provides a DRY approach to extracting and validating JWT tokens.

While it solves the exact problem go-jwt-middleware does, it doesn't have Gorilla context as a dependency and lets you use your own type of claims.

Usage

The API basically consists of three important functions and an Options struct:

  • Create a new instance with jaywt.New(&jaywt.Options{})
  • Extract & verify a JWT using jaywt.Get(request)
  • Extract & verify a JWT with custom claims using jaywt.GetWithClaims(request, &MyClaims{})
Dependencies

Examples

Create an instance (all options are optional):

j := jaywt.New(&jaywt.Options{
    // Defaults to 'nil'
    Keyfunc: func(_ *jwt.Token) (interface{}, error) {
        return []byte("secretAF"), nil
    },
    // Defaults to 'Authorization' header being: Bearer <token>
    Extractor: func(r *http.Request) (string, error) {
        return r.Header.Get("X-Authorization"), nil
    },
    // This is the default:
    SigningMethod: jwt.SigningMethodHS256,
})
Get JWT

Create any middleware you like! All you need is a http.Request. An example using gin:

// usage: api.Use(AuthMiddleware(p))
func AuthMiddleware(j *jaywt.Core) gin.HandlerFunc {
	return func(c *gin.Context) {
		token, err := j.Get(c.Request)
		if err != nil {
			c.AbortWithError(http.StatusUnauthorized, err)
			return
		}

		c.Set("userId", token.Claims.Subject)
		c.Next()
	}
}
Get JWT with claims

Pass your claims struct as a second argument to GetWithClaims:

type MyClaims struct {
	Doe string `json:"doe"`
	// important to allow jwt-go built-in validation:
	jwt.StandardClaims
}

func AuthMiddleware(j *jaywt.Core) gin.HandlerFunc {
	return func(c *gin.Context) {
		token, err := j.GetWithClaims(c.Request, &MyClaims{})
		if err != nil {
			c.AbortWithError(http.StatusUnauthorized, err)
			return
		}

		claims, ok := token.Claims.(*MyClaims) 
		if !ok {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		c.Set("userId", claims.Subject)
		c.Set("doe", claims.Doe)
		c.Next()
	}
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromAuthHeader

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

FromAuthHeader is the default extractor. It expects the 'Authorization' header to be in the form 'Bearer <token>'. If the header is non-existent or empty, it returns an empty string. Otherwise, if successful, returns the token part.

Types

type Core

type Core struct {
	Options *Options
}

Core is the main structure which provides an interface for checking the token.

func New

func New(o *Options) *Core

New returns a new Core with the given options. It supplies default options for some fields (check Options type for details).

func (*Core) Get

func (m *Core) Get(r *http.Request) (*jwt.Token, error)

Get extracts and validates the JWT token from the request. It returns the parsed token, if successful.

func (*Core) GetWithClaims

func (m *Core) GetWithClaims(r *http.Request, claims jwt.Claims) (*jwt.Token, error)

GetWithClaims extracts and validates the JWT token from the request, as well as the supplied claims. It returns the parsed token with the supplied claims, if successful.

type Options

type Options struct {
	// Function that will return the Key to the JWT, public key or shared secret.
	// Defaults to nil.
	Keyfunc jwt.Keyfunc
	// Function that will extract the JWT from the request.
	// Defaults to 'Authorization' header being of the form 'Bearer <token>'
	Extractor TokenExtractor
	// Which algorithm to use.
	// Defaults to jwt.SigningMethodHS256
	SigningMethod jwt.SigningMethod
}

Options determine the behavior of the checking functions.

type TokenExtractor

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

TokenExtractor is a function retrieving the raw token string from a request.

Jump to

Keyboard shortcuts

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