jwtmiddleware

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

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

Go to latest
Published: Feb 11, 2015 License: MIT Imports: 5 Imported by: 0

README

GO JWT Middleware

A middleware that will check that a JWT is sent on the Authorization header and will then set the content of the JWT into the user variable of the request.

This module lets you authenticate HTTP requests using JWT tokens in your Go Programming Language applications. JWTs are typically used to protect API endpoints, and are often issued using OpenID Connect.

Key Features

  • Ability to check the Authorization header for a JWT
  • Decode the JWT and set the content of it to the request context

Installing

go get github.com/auth0/go-jwt-middleware

Using it

You can use jwtmiddleware with default net/http as follows.

// main.go
package main

import (
    "net/http"
    "github.com/auth0/go-jwt-middleware"
    "github.com/gorilla/context"
)

var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    user := context.Get(r, "user")
    w.Write([]byte("hello world. This is an authenticated request"))
})

func main() {
    jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
      ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
        return []byte("My Secret Key"), nil
      },
    })

    app := jwtMiddleware.Handler(myHandler)
    http.ListenAndServe("0.0.0.0:3000", app)
}

You can also use it with Negroni as follows:

// main.go
package main

import (
    "net/http"
    "github.com/auth0/go-jwt-middleware"
    "github.com/gorilla/context"
)

var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    user := context.Get(r, "user")
    w.Write([]byte("hello world. This is an authenticated request"))
})

func main() {
    r := mux.NewRouter()

    jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
      ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
        decoded, err := base64.URLEncoding.DecodeString(os.Getenv("AUTH0_CLIENT_SECRET"))
        if err != nil {
          return nil, err
        }
        return decoded, nil
      },
    })

    r.HandleFunc("/ping", PingHandler)
    r.Handle("/secured/ping", negroni.New(
      negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
      negroni.Wrap(http.HandlerFunc(myHandler)),
    ))
    http.Handle("/", r)
    http.ListenAndServe(":3001", nil)
}

Options

type Options struct {
  // The function that will return the Key to validate the JWT. 
  // It can be either a shared secret or a public key.
  // Default value: nil
  ValidationKeyGetter jwt.Keyfunc
  // The name of the property in the request where the user information 
  // from the JWT will be stored.
  // Default value: "user"
  UserProperty string
  // The function that will be called when there's an error validating the token
  // Default value: https://github.com/auth0/go-jwt-middleware/blob/master/jwtmiddleware.go#L35
  ErrorHandler errorHandler
  // A boolean indicating if the credentials are required or not
  // Default value: false
  CredentialsOptional bool
}

Examples

You can check out working examples in the examples folder

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free Auth0 Account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func OnError

func OnError(w http.ResponseWriter, r *http.Request, err string)

Types

type JWTMiddleware

type JWTMiddleware struct {
	Options Options
}

func New

func New(options ...Options) *JWTMiddleware

New constructs a new Secure instance with supplied options.

func (*JWTMiddleware) CheckJWT

func (m *JWTMiddleware) CheckJWT(w http.ResponseWriter, r *http.Request) error

func (*JWTMiddleware) Handler

func (m *JWTMiddleware) Handler(h http.Handler) http.Handler

func (*JWTMiddleware) HandlerWithNext

func (m *JWTMiddleware) HandlerWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

Special implementation for Negroni, but could be used elsewhere.

type Options

type Options struct {
	// The function that will return the Key to validate the JWT.
	// It can be either a shared secret or a public key.
	// Default value: nil
	ValidationKeyGetter jwt.Keyfunc
	// The name of the property in the request where the user information
	// from the JWT will be stored.
	// Default value: "user"
	UserProperty string
	// The function that will be called when there's an error validating the token
	// Default value:
	ErrorHandler errorHandler
	// A boolean indicating if the credentials are required or not
	// Default value: false
	CredentialsOptional bool
}

Options is a struct for specifying configuration options for the middleware.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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