jwtauthapi

package
v0.0.0-...-707a7ba Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2023 License: MIT Imports: 12 Imported by: 0

README

jwtauthapi

This is the API you can embed into your own programs to validate incoming JWT. To use simply create a config struct with the settings you want.

If you specify a jwks URL to download from a background thread will be started to regulary update this file.

  {
    "endpoints": [ "/endpoint1", "/endpoint2"],
    "name": "Test 1 endpoint",
    "jwks": "http://static.helge.net/test/jwks.json",
    "allowed-algo": [ "RS256" ],
    "audience": [ "aud1", "aud2" ],
    "issuer": "golang"
}

Make sure that you specify issuer and audice so these fields can be validated.

In your code, use this as:

cc, err := jwtauthapi.LoadJsonFromFile("filename")
if err != nil {
	panic(err)
}
cc.Init()
// now check a JWT
err = cc.ValidateJWT(myjwttovalidate)
// if err != nil then validation failed and the reason is in the error code

http.Handle middelware

You can also use this library as a HTTP middleware so invalid requests are rejected before it reaches your code.

finalHandler := http.HandlerFunc(final) // this would be your code
mux.Handle("/", cc.JwtHandleFunc(finalHandler))
_ = http.ListenAndServe(":3000", mux)

your code in "final" will only be called if a valid token is presented.

During development

For initial development there is a small factory that you can use to issue and validate your own certificates. The JWT are signed using HA256 and with a shared secret that you specify. Look at factory_test.go for usage.

Documentation

Index

Constants

View Source
const Version = "0.0.9"

Variables

This section is empty.

Functions

func StringIn

func StringIn(a string, b *[]string) bool

StringIn returns true if a is in b

Types

type ClientConfig

type ClientConfig struct {
	Name        string   `json:"name" `        // descriptive name for this client
	JWKS        string   `json:"jwks"`         // URL to download the key set
	HMAC        string   `json:"hmac"`         // HMAC for HS* algorithms, only used if JWKS is empty
	AllowedAlgo []string `json:"allowed-algo"` // list of allowed signature algorithms - if empty any is allowed
	Audience    []string `json:"audience"`     // if this list is not empty, the JWT audience must match one in this list
	Issuer      string   `json:"issuer"`       // if not empty, this field must match iss in the JWT

	RequiredClaims    []string `json:"required-claims"`     // claims that must be present in the JWT
	TTL               int      `json:"ttl"`                 // cache jwks TTL; -1 = disable, 0 = use default, otherwise seconds between each refresh
	RefreshUnknownKid bool     `json:"refresh-unknown-kid"` // if true an unknown KID will attempt a new refresh of the jwkt
	// The properties below are only used by the web server in jwtauthrequest and http.Handle in jwtauthapi
	Debug      bool     `json:"debug,omitempty"`       // if true the reason for failure will be attached in the body as plain text, only used from the main program
	TrimPrefix string   `json:"trim-prefix,omitempty"` // prefix to be removed from token string before processing (like bearer), only used from the main program
	TokenName  string   `json:"token-name,omitempty"`  // name of header or query variable to get token from, only used from the main program
	Endpoints  []string `json:"endpoints,omitempty"`   // paths on this webserver that this client should accept - if empty http.Handle in jwtauthapi will accept all paths
	// contains filtered or unexported fields
}

ClientConfig describes one specific client configuration endpoint

func LoadJsonFromFile

func LoadJsonFromFile(fn string) (cc *ClientConfig, err error)

LoadJsonFromFile reads a ClientConfig JSON formatted file from disk

func (*ClientConfig) Init

func (c *ClientConfig) Init() (err error)

func (*ClientConfig) JwtHandleFunc

func (client *ClientConfig) JwtHandleFunc(next http.Handler) http.Handler

JwtHandleFunc returns an http.Handler that you can use as your middleware to enforce authentication before reaching your application/code.

Use like this:

finalHandler := http.HandlerFunc(final) // this would be your code

mux.Handle("/", cc.JwtHandleFunc(finalHandler))

_ = http.ListenAndServe(":3000", mux)

func (*ClientConfig) ValidateJWT

func (c *ClientConfig) ValidateJWT(input string) (err error)

ValidateJWT returns an error if token failed validation

type TokenFactory

type TokenFactory struct {
	HMAC       []byte                 `json:"hmac"`   // shared secret
	Issuer     string                 `json:"iss"`    // issuer of token
	ExpireTime int64                  `json:"exp"`    // time to add to JWT expiration in seconds
	Audience   string                 `json:"aud"`    // audience field
	Extras     map[string]interface{} `json:"claims"` // extra fields to add to the claim
}

TokenFactory represents the configuration needed to issue now tokens using HS256

func (*TokenFactory) GetClientConfig

func (t *TokenFactory) GetClientConfig() ClientConfig

GetClientConfig returns a client config from the factory

func (*TokenFactory) Issue

func (t *TokenFactory) Issue() (string, error)

Issue issues a new token based on the current token factory

func (*TokenFactory) IssueWithClaims

func (t *TokenFactory) IssueWithClaims(customClaims map[string]interface{}) (string, error)

IssueWithClaims issues a new token based on the current token factory with customClaims added last allowing them to override standard claims if you want.

Jump to

Keyboard shortcuts

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