jwt

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

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

Go to latest
Published: Oct 1, 2015 License: MIT Imports: 7 Imported by: 1

README

This is a fork of StephanDollberg/go-json-rest-middleware-jwt with the intent to return more detailed auth errors in the JSON return data, including errors from dgrijalva/jwt-go.

Example return from curl:

>curl -i -H "Authorization:Bearer eyJhbGci ...... wMzM"  http://localhost:8080/somejwt/login

HTTP/1.1 401 Unauthorized
Content-Type: application/json
Www-Authenticate: JWT realm=HolyRealm
X-Powered-By: go-json-rest
Date: Mon, 07 Sep 2015 02:35:41 GMT
Content-Length: 103

{
  "Error": "Not Authorized",
  "JwtValidationCode": 8,
  "JwtValidationMessage": "token is expired"
}

Its considered alpha, the functionality is implemented but no testcases yet. Debug Printf's need to be removed - but if you try it, it should not burn down your house.

Update 18.9.2015

Its considered beta now - debug printfs have been removed, error messages have been moved into

if debug ..

statements.

Example jwt middleware init:

jwt_middleware = &jwt.JWTMiddleware{
	Key:        []byte("THIS SECRET STRING"),
	Realm:      "THISREALM",
	DebugLevel: 3,
	Timeout:    time.Hour,
	MaxRefresh: time.Hour * 24,
	Authenticator: func(username string, password string) bool {
		if username == "admin" && password == "admin" {
			return true
		}
	},
	Authorizator: func(username string, request *rest.Request) bool {
		return true
	},
	// Payload / claims
	PayloadFunc: func(userId string) map[string]interface{} {
		claims := make(map[string]interface{})
		claims["UserLevel"] = "9001"
		return claims
	},
}

The following text is from the original: StephanDollberg/go-json-rest-middleware-jwt

JWT Middleware for Go-Json-Rest

godoc license

This is a middleware for Go-Json-Rest.

It uses jwt-go to provide a jwt authentication middleware. It provides additional handler functions to provide the login api that will generate the token and an additional refresh handler that can be used to refresh tokens.

An example can be found in the Go-Json-Rest Examples repo.

Documentation

Overview

Package jwt provides Json-Web-Token authentication for the go-json-rest framework

Index

Constants

View Source
const (
	AuthJwtErrorNotValidYet         uint32 = jwt.ValidationErrorNotValidYet << iota // error const start after jwt errors
	AuthJwtErrorLoginFailed                                                         // login failed
	AuthJwtErrorAuthorizationFailed                                                 // Not authorized for resource failed
	AuthJwtErrorInternalError
)

The errors that might occur inside auth_jwt and not inside dgrijalva/jwt-go

Variables

This section is empty.

Functions

func ExtractClaims

func ExtractClaims(request *rest.Request) map[string]interface{}

Helper function to extract the JWT claims

Types

type AuthJwtError

type AuthJwtError struct {
	ErrorCode uint32 // numeric error, see jwt.ValidationError... constants
	// contains filtered or unexported fields
}

An error generated by the auth jwt middleware, not by dgrijalva/jwt-go

func (AuthJwtError) Error

func (e AuthJwtError) Error() string

AuthJwtError is an error type

type JWTMiddleware

type JWTMiddleware struct {
	// Realm name to display to the user. Required.
	Realm string

	// Sets the debug level: 0=none, 1=errors, 2=warnings, 3=infos
	DebugLevel int

	// signing algorithm - possible values are HS256, HS384, HS512
	// Optional, default is HS256.
	SigningAlgorithm string

	// Secret key used for signing. Required.
	Key []byte

	// Duration that a jwt token is valid. Optional, defaults to one hour.
	Timeout time.Duration

	// This field allows clients to refresh their token until MaxRefresh has passed.
	// Note that clients can refresh their token in the last moment of MaxRefresh.
	// This means that the maximum validity timespan for a token is MaxRefresh + Timeout.
	// Optional, defaults to 0 meaning not refreshable.
	MaxRefresh time.Duration

	// Callback function that should perform the authentication of the user based on userId and
	// password. Must return true on success, false on failure. Required.
	Authenticator func(userId string, password string) bool

	// Callback function that should perform the authorization of the authenticated user. Called
	// only after an authentication success. Must return true on success, false on failure.
	// Optional, default to success.
	Authorizator func(userId string, request *rest.Request) bool

	// Callback function that will be called during login.
	// Using this function it is possible to add additional payload data to the webtoken.
	// The data is then made available during requests via request.Env["JWT_PAYLOAD"].
	// Note that the payload is not encrypted.
	// The attributes mentioned on jwt.io can't be used as keys for the map.
	// Optional, by default no additional data will be set.
	PayloadFunc func(userId string) map[string]interface{}
}

JWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userId is made available as request.Env["REMOTE_USER"].(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX

func (*JWTMiddleware) LoginHandler

func (mw *JWTMiddleware) LoginHandler(writer rest.ResponseWriter, request *rest.Request)

Handler that clients can use to get a jwt token. Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}. Reply will be of the form {"token": "TOKEN"}.

func (*JWTMiddleware) MiddlewareFunc

func (mw *JWTMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc

MiddlewareFunc makes JWTMiddleware implement the Middleware interface.

func (*JWTMiddleware) RefreshHandler

func (mw *JWTMiddleware) RefreshHandler(writer rest.ResponseWriter, request *rest.Request)

Handler that clients can use to refresh their token. The token still needs to be valid on refresh. Shall be put under an endpoint that is using the JWTMiddleware. Reply will be of the form {"token": "TOKEN"}.

Jump to

Keyboard shortcuts

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