oidc

package module
v0.0.0-...-1f03736 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2022 License: MIT Imports: 7 Imported by: 2

README

oidc-jwt-go

OpenID Connect package to secure your API using JWT Bearer tokens. It uses dgrijalva/jwt-go for jwt decoding and signature verification

Installation

go get "github.com/osstotalsoft/oidc-jwt-go"

Usage

import (
	"log"
	"net/http"

	jwtRequest "github.com/golang-jwt/jwt/request"
	"github.com/osstotalsoft/oidc-jwt-go"
)

func middleware() func(next http.Handler) http.Handler {
	authority := "https://accounts.google.com" //or other OIDC provider
	audience := "YOUR_API_NAME"

	secretProvider := oidc.NewOidcSecretProvider(discovery.NewClient(discovery.Options{authority}))
	validator := oidc.NewJWTValidator(jwtRequest.OAuth2Extractor, secretProvider, audience, authority)

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			token, err := validator(request)
			if err != nil {
				log.Error("AuthorizationFilter: Token is not valid", err)
				UnauthorizedWithHeader(writer, err.Error())
				return
			}
			next.ServeHttp(writer, request)
		})
	}
}

//UnauthorizedWithHeader adds to the response a WWW-Authenticate header and returns a StatusUnauthorized error
func UnauthorizedWithHeader(writer http.ResponseWriter, err string) {
	writer.Header().Set("WWW-Authenticate", "Bearer error=\"invalid_token\", error_description=\""+err+"\"")
	http.Error(writer, "", http.StatusUnauthorized)
}

Caching

The Secret Provider uses a simple sync.Map, with no expiration, to cache the rsa.PublicKey by a Key ID string

TODO

Similar projects

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewJWTValidator

func NewJWTValidator(extractor jwtRequest.Extractor, provider SecretProvider, audience string, authority string) func(request *http.Request) (*jwt.Token, error)

func NewOidcSecretProvider

func NewOidcSecretProvider(configurationDiscoverer discovery.Discoverer) *oidcSecretProvider

Types

type SecretProvider

type SecretProvider interface {
	GetSecret(tokenKeyId string) (key *rsa.PublicKey, err error)
}

func NewKeyProvider

func NewKeyProvider(publicKey *rsa.PublicKey) SecretProvider

NewKeyProvider provide a simple passphrase key provider.

type SecretProviderFunc

type SecretProviderFunc func(tokenKeyId string) (*rsa.PublicKey, error)

func (SecretProviderFunc) GetSecret

func (f SecretProviderFunc) GetSecret(tokenKeyId string) (*rsa.PublicKey, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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