jwt

package
v2.11.5 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2022 License: MIT Imports: 9 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"
	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"

	"github.com/shaj13/libcache"
	_ "github.com/shaj13/libcache/lru"
)

func main() {
	u := auth.NewUserInfo("example", "example", nil, nil)
	c := libcache.LRU.New(0)
	s := jwt.StaticSecret{
		ID:        "id",
		Algorithm: jwt.HS256,
		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"
	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	"github.com/shaj13/go-guardian/v2/auth/strategies/token"

	"github.com/shaj13/libcache"
	_ "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",
		Algorithm: jwt.HS256,
		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

View Source
const (
	// EdDSA signature algorithm.
	EdDSA = "EdDSA"
	// HS256 signature algorithm -- HMAC using SHA-256.
	HS256 = "HS256"
	// HS384 signature algorithm -- HMAC using SHA-384.
	HS384 = "HS384"
	// HS512 signature algorithm -- HMAC using SHA-512.
	HS512 = "HS512"
	// RS256 signature algorithm -- RSASSA-PKCS-v1.5 using SHA-256.
	RS256 = "RS256"
	// RS384 signature algorithm -- RSASSA-PKCS-v1.5 using SHA-384.
	RS384 = "RS384"
	// RS512 signature algorithm -- RSASSA-PKCS-v1.5 using SHA-512.
	RS512 = "RS512"
	// ES256 signature algorithm -- ECDSA using P-256 and SHA-256.
	ES256 = "ES256"
	// ES384 signature algorithm -- ECDSA using P-384 and SHA-384.
	ES384 = "ES384"
	// ES512 signature algorithm -- ECDSA using P-521 and SHA-512.
	ES512 = "ES512"
	// PS256 signature algorithm -- RSASSA-PSS using SHA256 and MGF1-SHA256.
	PS256 = "PS256"
	// PS384 signature algorithm -- RSASSA-PSS using SHA384 and MGF1-SHA384.
	PS384 = "PS384"
	// PS512 signature algorithm -- RSASSA-PSS using SHA512 and MGF1-SHA512.
	PS512 = "PS512"
)

Variables

View Source
var (
	// ErrMissingKID is returned by Authenticate Strategy method,
	// when failed to retrieve kid from token header.
	ErrMissingKID = jwt.ErrMissingKID

	// ErrInvalidAlg is returned by Authenticate Strategy method,
	// when jwt token alg header does not match key algorithm.
	ErrInvalidAlg = jwt.ErrInvalidAlg
)

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/go-guardian/v2/auth/strategies/jwt"

	"github.com/shaj13/libcache"
	_ "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/go-guardian/v2/auth/strategies/jwt"

	"github.com/shaj13/libcache"
	_ "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), no default value.

Example
package main

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

	"github.com/shaj13/libcache"
	_ "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"
	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
	"github.com/shaj13/go-guardian/v2/auth/strategies/token"

	"github.com/shaj13/libcache"
	_ "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 algorithm.
	Get(kid string) (key interface{}, algorithm string, 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"
	"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"

	"github.com/shaj13/libcache"
	_ "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{}, alg string, err error) {
	s, ok := r.Secrtes[kid]
	if ok {
		return s, jwt.HS256, nil
	}
	return 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
	Algorithm string
}

StaticSecret implements the SecretsKeeper and holds only a single secret.

func (StaticSecret) Get

func (s StaticSecret) Get(kid string) (key interface{}, algorithm string, err error)

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

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