jwt

package
v2.5.2 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2021 License: MIT Imports: 7 Imported by: 8

Documentation

Overview

Package jwt provides authentication strategy, to authenticate HTTP requests based on jwt token.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/shaj13/go-guardian/v2/auth"

	gojwt "github.com/dgrijalva/jwt-go/v4"
	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	u := auth.NewUserInfo("example", "example", nil, nil)
	c := libcache.LRU.New(0)
	s := jwt.StaticSecret{
		ID:     "id",
		Method: gojwt.SigningMethodHS256,
		Secret: []byte("your secret"),
	}

	token, err := jwt.IssueAccessToken(u, s)
	strategy := jwt.New(c, s)

	fmt.Println(err)

	// user request
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("Authorization", "Bearer "+token)
	user, err := strategy.Authenticate(r.Context(), r)
	fmt.Println(user.GetID(), err)

}
Output:

<nil>
example <nil>
Example (Scope)
package main

import (
	"fmt"
	"net/http"

	"github.com/shaj13/go-guardian/v2/auth/strategies/token"

	"github.com/shaj13/go-guardian/v2/auth"

	gojwt "github.com/dgrijalva/jwt-go/v4"
	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	opt := token.SetScopes(token.NewScope("read:example", "/example", "GET"))
	ns := jwt.SetNamedScopes("read:example")
	u := auth.NewUserInfo("example", "example", nil, nil)
	c := libcache.LRU.New(0)
	s := jwt.StaticSecret{
		ID:     "id",
		Method: gojwt.SigningMethodHS256,
		Secret: []byte("your secret"),
	}

	token, err := jwt.IssueAccessToken(u, s, ns)
	strategy := jwt.New(c, s, opt)

	fmt.Println(err)

	// user request
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("Authorization", "Bearer "+token)
	_, err = strategy.Authenticate(r.Context(), r)
	fmt.Println(err)

}
Output:

<nil>
strategies/token: The access token scopes do not grant access to the requested resource

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingKID is returned by Authenticate Strategy method,
	// when failed to retrieve kid from token header.
	ErrMissingKID = errors.New("strategies/jwt: Token missing " + headerKID + " header")

	// ErrInvalidAlg is returned by Authenticate Strategy method,
	// when jwt token alg header does not match key algorithm.
	ErrInvalidAlg = errors.New("strategies/jwt: Invalid signing algorithm, token alg header does not match key algorithm")
)

Functions

func GetAuthenticateFunc

func GetAuthenticateFunc(s SecretsKeeper, opts ...auth.Option) token.AuthenticateFunc

GetAuthenticateFunc return function to authenticate request using jwt token. The returned function typically used with the token strategy.

func IssueAccessToken

func IssueAccessToken(info auth.Info, s SecretsKeeper, opts ...auth.Option) (string, error)

IssueAccessToken issue jwt access token for the provided user info.

func New

func New(c auth.Cache, s SecretsKeeper, opts ...auth.Option) auth.Strategy

New return strategy authenticate request using jwt token.

New is similar to:

fn := jwt.GetAuthenticateFunc(secretsKeeper, opts...)
token.New(fn, cache, opts...)

func SetAudience

func SetAudience(aud string) auth.Option

SetAudience sets token audience(aud), no default value.

Example
package main

import (
	"github.com/shaj13/go-guardian/v2/auth"

	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	aud := jwt.SetAudience("example-aud")
	u := auth.NewUserInfo("example", "example", nil, nil)
	s := jwt.StaticSecret{}
	c := libcache.LRU.New(0)

	_, _ = jwt.IssueAccessToken(u, s, aud)
	_ = jwt.New(c, s, aud)
}
Output:

func SetExpDuration

func SetExpDuration(d time.Duration) auth.Option

SetExpDuration sets token exp duartion, Default Value 5 min.

Example
package main

import (
	"time"

	"github.com/shaj13/go-guardian/v2/auth"

	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	exp := jwt.SetExpDuration(time.Hour)
	u := auth.NewUserInfo("example", "example", nil, nil)
	s := jwt.StaticSecret{}
	c := libcache.LRU.New(0)

	_, _ = jwt.IssueAccessToken(u, s, exp)
	_ = jwt.New(c, s, exp)
}
Output:

func SetIssuer

func SetIssuer(iss string) auth.Option

SetIssuer sets token issuer(iss), Default Value "go-guardian".

Example
package main

import (
	"github.com/shaj13/go-guardian/v2/auth"

	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	iss := jwt.SetIssuer("example-iss")
	u := auth.NewUserInfo("example", "example", nil, nil)
	s := jwt.StaticSecret{}
	c := libcache.LRU.New(0)

	_, _ = jwt.IssueAccessToken(u, s, iss)
	_ = jwt.New(c, s, iss)
}
Output:

func SetNamedScopes added in v2.4.3

func SetNamedScopes(scp ...string) auth.Option

SetNamedScopes sets the access token scopes,

Example
package main

import (
	"github.com/shaj13/go-guardian/v2/auth/strategies/token"

	"github.com/shaj13/go-guardian/v2/auth"

	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	u := auth.NewUserInfo("example", "example", nil, nil)
	ns := jwt.SetNamedScopes("read:example")
	// get jwt scope verification option
	opt := token.SetScopes(token.NewScope("read:example", "/example", "GET"))
	s := jwt.StaticSecret{}
	c := libcache.LRU.New(0)

	_, _ = jwt.IssueAccessToken(u, s, ns)
	_ = jwt.New(c, s, opt)
}
Output:

Types

type SecretsKeeper

type SecretsKeeper interface {
	// KID return's secret/key id.
	// KID must return the most recently used id if more than one secret/key exists.
	// https://tools.ietf.org/html/rfc7515#section-4.1.4
	KID() string
	// Get return's secret/key and the corresponding sign method.
	Get(kid string) (key interface{}, m jwt.SigningMethod, err error)
}

SecretsKeeper hold all secrets/keys to sign and parse JWT token

Example
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/shaj13/go-guardian/v2/auth"

	gojwt "github.com/dgrijalva/jwt-go/v4"
	"github.com/shaj13/libcache"

	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	_ "github.com/shaj13/libcache/lru"
)

type RotatedSecrets struct {
	Secrtes          map[string][]byte
	LatestID         string
	RotationDuration time.Duration
	LastRotation     time.Time
}

func (r RotatedSecrets) KID() string {
	if time.Now().After(r.LastRotation) {
		r.LastRotation = time.Now().Add(r.RotationDuration)
		r.LatestID = "your generated id"
		r.Secrtes[r.LatestID] = []byte("your generated secrets")
	}
	return r.LatestID
}

func (r RotatedSecrets) Get(kid string) (key interface{}, m gojwt.SigningMethod, err error) {
	s, ok := r.Secrtes[kid]
	if ok {
		return s, gojwt.SigningMethodHS256, nil
	}
	return nil, nil, fmt.Errorf("Invalid KID %s", kid)
}

func main() {
	// The example shows how to create your custom secrets keeper to rotate secrets.
	s := RotatedSecrets{
		Secrtes: make(map[string][]byte),
	}
	u := auth.NewUserInfo("example", "example", nil, nil)
	c := libcache.LRU.New(0)

	token, err := jwt.IssueAccessToken(u, s)
	strategy := jwt.New(c, s)

	fmt.Println(err)

	// user request
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("Authorization", "Bearer "+token)
	user, err := strategy.Authenticate(r.Context(), r)
	fmt.Println(user.GetID(), err)

}
Output:

<nil>
example <nil>

type StaticSecret

type StaticSecret struct {
	Secret interface{}
	ID     string
	Method jwt.SigningMethod
}

StaticSecret implements the SecretsKeeper and holds only a single secret.

func (StaticSecret) Get

func (s StaticSecret) Get(kid string) (key interface{}, m jwt.SigningMethod, err error)

Get return's secret/key and the corresponding sign method.

func (StaticSecret) KID

func (s StaticSecret) KID() string

KID return's secret/key id.

Jump to

Keyboard shortcuts

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