cidaasinterceptor

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2023 License: MIT Imports: 15 Imported by: 0

README

pipeline status coverage report License

Logo

About cidaas:

cidaas is a fast and secure Cloud Identity & Access Management solution that standardises what’s important and simplifies what’s complex.

Feature set includes:

  • Single Sign On (SSO) based on OAuth 2.0, OpenID Connect, SAML 2.0
  • Multi-Factor-Authentication with more than 14 authentication methods, including TOTP and FIDO2
  • Passwordless Authentication
  • Social Login (e.g. Facebook, Google, LinkedIn and more) as well as Enterprise Identity Provider (e.g. SAML or AD)
  • Security in Machine-to-Machine (M2M) and IoT

How to install

Version 1.x.x

go get github.com/Cidaas/go-interceptor

This version allows to secure your APIs by passing scopes or roles to the interceptor which can be either validated by introspecting the access token or checking its signature.

Version 2.x.x

go get github.com/Cidaas/go-interceptor/v2

This version allows to secure your APIs by passing security options to the interceptor which can be either validated by introspecting the access token or checking its signature. You can pass the following options to the interceptor:

For the signature validation only the scopes can be validated in a strict way

// SecurityOptions which should be passsed to restrict the api access
type SecurityOptions struct {
	Roles                 []string                 // roles which are allowed to access this api
	Scopes                []string                 // scopes which are allowed to acces this api
	Groups                []GroupValidationOptions // groups which are allowed to acces this api (only possible with introspect)
	AllowAnonymousSub     bool                     // false (by default) indicates that tokens which have an anonymous sub are rejected, true indicates that tokens which have an ANONYMOUS sub are allowed (only possible with the signature check for now)
	StrictRoleValidation  bool                     // by default false, true indicates that all provided roles must match (only possible with introspect)
	StrictScopeValidation bool                     // by default false, true indicates that all provided scopes must match (also possible with the signature check)
	StrictGroupValidation bool                     // by default false, true indicates that all provided groups must match (only possible with introspect)
	StrictValidation      bool                     // by default false, true indicates that all provided roles, scopes and groups must match (the signature check just checks for the scopes)
}

// GroupValidationOptions provides options to allow API access only to certain groups
type GroupValidationOptions struct {
	GroupID              string   `json:"groupId"`              // the group id to match
	GroupType            string   `json:"groupType"`            // the group type to match
	Roles                []string `json:"roles"`                // the roles to match
	StrictRoleValidation bool     `json:"strictRoleValidation"` // true indicates that all roles must match
	StrictValidation     bool     `json:"strictValidation"`     // true indicates that the group id, group type and all roles must match
}
Breaking changes
  • Instead of passing the scopes and roles in order to verify the token, you now need to pass an object with different options, which is explained above
  • Now tokens which have NO SUB are rejected by default, if you want to allow this you need to enable the SecurityOptions.AllowAnonymousSub flag, which is false by default

Usage

The cidaas go interceptor can be used to secure APIs which use the net/http package or the fiber web framework in golang.

net/http

The following examples will show how to use the interceptor if you are using the net/http package for your APIs.

net/http

The following examples will show how to use the interceptor if you are using the net/http package for your APIs.

Attached an example how to secure an API with scopes and roles based on the signature of a token:

Version 1.x.x
func get(w http.ResponseWriter, r *http.Request) {
	// set response to ok and return Status ok and response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(respJSON))
	return
}

func main() {
	r := mux.NewRouter()
	api := r.PathPrefix("/api/v1").Subrouter()
	// Base URI is mandatory, ClientID is optional, if ClientID is set the interceptor will only allow requests from this Client
	cidaasInterceptor, err := cidaasinterceptor.New(cidaasinterceptor.Options{BaseURI: "https://base.cidaas.de", ClientID: "clientID"})
	if err != nil {
		log.Panicf("Initialization of cidaas interceptor failed! Error: %v", err)
		panic("Panic!")
	}
	getHandler := http.HandlerFunc(get)
	api.Handle("/", cidaasInterceptor.VerifyTokenBySignature(getHandler, []string{"profile", "cidaas:api_scope"}, []string{"role:Admin"})).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}
Version 2.x.x
func get(w http.ResponseWriter, r *http.Request) {
	// set response to ok and return Status ok and response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(respJSON))
	return
}

func main() {
	r := mux.NewRouter()
	api := r.PathPrefix("/api/v2").Subrouter()
	// Base URI is mandatory, ClientID is optional, if ClientID is set the interceptor will only allow requests from this Client
	cidaasInterceptor, err := cidaasinterceptor.New(cidaasinterceptor.Options{BaseURI: "https://base.cidaas.de", ClientID: "clientID"})
	if err != nil {
		log.Panicf("Initialization of cidaas interceptor failed! Error: %v", err)
		panic("Panic!")
	}
	getHandler := http.HandlerFunc(get)
	api.Handle("/", cidaasInterceptor.VerifyTokenBySignature(getHandler, cidaasinterceptor.SecurityOptions{
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	})).Methods(http.MethodGet)
	api.Handle("/user", cidaasInterceptor.VerifyTokenBySignature(getHandler, cidaasinterceptor.SecurityOptions{
		AllowAnonymousSub: true, // add this flag if you want to allow tokens with an anonymous sub
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	})).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}

Attached an example how to secure an API with scopes and roles based on an introspect call to the cidaas instance:

Version 1.x.x
func get(w http.ResponseWriter, r *http.Request) {
	// set response to ok and return Status ok and response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(respJSON))
	return
}

func main() {
	r := mux.NewRouter()
	api := r.PathPrefix("/api/v1").Subrouter()
	// Base URI is mandatory, ClientID is optional, if ClientID is set the interceptor will only allow requests from this Client
	cidaasInterceptor, err := cidaasinterceptor.New(cidaasinterceptor.Options{BaseURI: "https://base.cidaas.de", ClientID: "clientID"})
	if err != nil {
		log.Panicf("Initialization of cidaas interceptor failed! Error: %v", err)
		panic("Panic!")
	}
	getHandler := http.HandlerFunc(get)
	api.Handle("", cidaasInterceptor.VerifyTokenByIntrospect(getHandler, []string{"profile", "cidaas:api_scope"}, nil)).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}
Version 2.x.x
func get(w http.ResponseWriter, r *http.Request) {
    ...
	// set response to ok and return Status ok and response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(respJSON))
	return
}

func main() {
	r := mux.NewRouter()
	api := r.PathPrefix("/api/v1").Subrouter()
	// Base URI is mandatory, ClientID is optional, if ClientID is set the interceptor will only allow requests from this Client
	cidaasInterceptor, err := cidaasinterceptor.New(cidaasinterceptor.Options{BaseURI: "https://base.cidaas.de", ClientID: "clientID"})
	if err != nil {
		log.Panicf("Initialization of cidaas interceptor failed! Error: %v", err)
		panic("Panic!")
	}
	getHandler := http.HandlerFunc(get)
	api.Handle("", cidaasInterceptor.VerifyTokenByIntrospect(getHandler, cidaasinterceptor.SecurityOptions{
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	})).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}

Attached an example how to secure an API with groups based on an introspect call to the cidaas instance:

Version 1.x.x

Not supported

Version 2.x.x
func get(w http.ResponseWriter, r *http.Request) {
    ...
	// set response to ok and return Status ok and response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(respJSON))
	return
}

func main() {
	r := mux.NewRouter()
	api := r.PathPrefix("/api/v1").Subrouter()
	// Base URI is mandatory, ClientID is optional, if ClientID is set the interceptor will only allow requests from this Client
	cidaasInterceptor, err := cidaasinterceptor.New(cidaasinterceptor.Options{BaseURI: "https://base.cidaas.de", ClientID: "clientID"})
	if err != nil {
		log.Panicf("Initialization of cidaas interceptor failed! Error: %v", err)
		panic("Panic!")
	}
	getHandler := http.HandlerFunc(get)
	api.Handle("", cidaasInterceptor.VerifyTokenByIntrospect(getHandler, cidaasinterceptor.SecurityOptions{
		Groups: []cidaasinterceptor.GroupValidationOptions{{GroupID: "yourGroupID"}},
	})).Methods(http.MethodGet)
	api.Handle("/user", cidaasInterceptor.VerifyTokenByIntrospect(getHandler, cidaasinterceptor.SecurityOptions{
		AllowAnonymousSub: true, // add this flag if you want to allow tokens with an anonymous sub
		Groups: []cidaasinterceptor.GroupValidationOptions{{GroupID: "yourGroupID"}},
	})).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}

Fiber

The following examples will show how to use the interceptor if you are using the fiber web framework for your APIs.

How to install
go get -u github.com/gofiber/fiber/v2

Attached an example how to secure an API with scopes and roles based on the signature token validation and also with the introspect call:

Version 1.x.x
func CreateApp() (*fiber.App, error) {
	interceptor, err := cidaasinterceptor.NewFiberInterceptor(cidaasinterceptor.Options{
		BaseURI:  BaseUrl,
		ClientID: Client_id,
	})
	if err != nil {
		ls.Fatal().Err(err).Msg("can't initialize interceptor")
	}
	app := fiber.New()
	root := app.Group(fmt.Sprintf("/%s", base.ServiceName))
	root.Post("/user", interceptor.VerifyTokenBySignature([]string{"profile", "cidaas:api_scope"}, []string{"role:Admin"}), handler.UserHandler)
	root.Post("/user", interceptor.VerifyTokenByIntrospect([]string{"profile", "cidaas:api_scope"}, []string{"role:Admin"}), handler.UserHandler)
	return app, nil
}

func main()  {
    app, err := CreateApp()
	if err != nil {
		panic(err)
    }
	app.Listen(":3000")
}
Version 2.x.x
func CreateApp() (*fiber.App, error) {
	interceptor, err := cidaasinterceptor.NewFiberInterceptor(cidaasinterceptor.Options{
		BaseURI:  BaseUrl,
		ClientID: Client_id,
	})
	if err != nil {
		ls.Fatal().Err(err).Msg("can't initialize interceptor")
	}
	app := fiber.New()
	root := app.Group(fmt.Sprintf("/%s", base.ServiceName))
	root.Post("/user", interceptor.VerifyTokenBySignature(cidaasinterceptor.SecurityOptions{
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	}), handler.UserHandler)
	root.Post("/groups", interceptor.VerifyTokenBySignature(cidaasinterceptor.SecurityOptions{
		AllowAnonymousSub: true, // add this flag if you want to allow tokens with an anonymous sub
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	}), handler.UserHandler)
	root.Post("/user", interceptor.VerifyTokenByIntrospect(cidaasinterceptor.SecurityOptions{
		Scopes: []string{"your scope"},
		Roles: []string{"role:Admin"},
	}), handler.UserHandler)
	return app, nil
}

func main()  {
    app, err := CreateApp()
	if err != nil {
		panic(err)
    }
	app.Listen(":3000")
}

Attached an example how to secure an API with groups with the introspect call:

Version 1.x.x

Not supported

Version 2.x.x
func CreateApp() (*fiber.App, error) {
	interceptor, err := cidaasinterceptor.NewFiberInterceptor(cidaasinterceptor.Options{
		BaseURI:  BaseUrl,
		ClientID: Client_id,
	})
	if err != nil {
		ls.Fatal().Err(err).Msg("can't initialize interceptor")
	}
	app := fiber.New()
	root := app.Group(fmt.Sprintf("/%s", base.ServiceName))
	root.Post("/user", interceptor.VerifyTokenByIntrospect(cidaasinterceptor.SecurityOptions{
		Groups: []cidaasinterceptor.GroupValidationOptions{{GroupID: "yourGroupID"}},
	}), handler.UserHandler)
	return app, nil
}

func main()  {
    app, err := CreateApp()
	if err != nil {
		panic(err)
    }
	app.Listen(":3000")
}

Documentation

Index

Constants

View Source
const FiberTokenDataKey = "tokendata"

FiberTokenDataKey key to access the token data ofthe request context

Variables

This section is empty.

Functions

This section is empty.

Types

type CidaasInterceptor

type CidaasInterceptor struct {
	Options Options
	// contains filtered or unexported fields
}

CidaasInterceptor to secure APIs based on OAuth 2.0 for the net/http based api requests

func New

func New(opts Options) (*CidaasInterceptor, error)

New returns a newly constructed cidaasInterceptor instance with the provided options

func (*CidaasInterceptor) VerifyTokenByIntrospect

func (m *CidaasInterceptor) VerifyTokenByIntrospect(next http.Handler, apiOptions SecurityOptions) http.Handler

VerifyTokenByIntrospect (check for exp time, issuer and scopes, roles and groups)

func (*CidaasInterceptor) VerifyTokenBySignature

func (m *CidaasInterceptor) VerifyTokenBySignature(next http.Handler, apiOptions SecurityOptions) http.Handler

VerifyTokenBySignature (check for exp time and scopes and roles, no groups)

type ContextKey

type ContextKey int

ContextKey used to add request context

const TokenDataKey ContextKey = 3941119

TokenDataKey used to add the token data to the request context

type FiberInterceptor

type FiberInterceptor struct {
	Options Options
	// contains filtered or unexported fields
}

FiberInterceptor to secure APIs based on OAuth 2.0 with fiber

func NewFiberInterceptor

func NewFiberInterceptor(opts Options) (*FiberInterceptor, error)

NewFiberInterceptor returns a newly constructed cidaasInterceptor instance with the provided options

func (*FiberInterceptor) VerifyTokenByIntrospect

func (m *FiberInterceptor) VerifyTokenByIntrospect(apiOptions SecurityOptions) fiber.Handler

VerifyTokenByIntrospect (check for exp time, issuer and scopes and roles)

func (*FiberInterceptor) VerifyTokenBySignature

func (m *FiberInterceptor) VerifyTokenBySignature(apiOptions SecurityOptions) fiber.Handler

VerifyTokenBySignature (check for exp time and scopes and roles)

type GroupDetails

type GroupDetails struct {
	GroupID string   `json:"groupId,omitempty"` // group id
	Roles   []string `json:"roles,omitempty"`   // roles of user in this group
}

GroupDetails represents the group details returned in token

type GroupValidationOptions

type GroupValidationOptions struct {
	GroupID              string   `json:"groupId"`              // the group id to match
	GroupType            string   `json:"groupType"`            // the group type to match
	Roles                []string `json:"roles"`                // the roles to match
	StrictRoleValidation bool     `json:"strictRoleValidation"` // true indicates that all roles must match
	StrictValidation     bool     `json:"strictValidation"`     // true indicates that the group id, group type and all roles must match
}

GroupValidationOptions provides options to allow API access only to certain groups

type JSONWebKey

type JSONWebKey struct {
	Kty string `json:"kty"`
	Kid string `json:"kid"`
	Use string `json:"use"`
	N   string `json:"n"`
	E   string `json:"e"`
	Alg string `json:"alg"`
}

JSONWebKey struct containing data of a key to verify a signature of token

type Jwks

type Jwks struct {
	Keys []JSONWebKey `json:"keys"`
}

Jwks struct containing a list of keys to verify a signature of token

type Options

type Options struct {
	BaseURI  string
	ClientID string
	Debug    bool
}

Options passed to the Interceptor (Base URI, ClientID)

type SecurityOptions

type SecurityOptions struct {
	Roles                 []string                 // roles which are allowed to access this api
	Scopes                []string                 // scopes which are allowed to acces this api
	Groups                []GroupValidationOptions // groups which are allowed to acces this api (only possible with introspect)
	AllowAnonymousSub     bool                     // false (by default) indicates that tokens which have an anonymous sub are rejected, true indicates that tokens which have an ANONYMOUS sub are allowed (only possible with the signature check for now)
	StrictRoleValidation  bool                     // by default false, true indicates that all provided roles must match (only possible with introspect)
	StrictScopeValidation bool                     // by default false, true indicates that all provided scopes must match (also possible with the signature check)
	StrictGroupValidation bool                     // by default false, true indicates that all provided groups must match (only possible with introspect)
	StrictValidation      bool                     // by default false, true indicates that all provided roles, scopes and groups must match (the signature check just checks for the scopes)
}

SecurityOptions which should be passsed to restrict the api access

type TokenData

type TokenData struct {
	Sub string
	Aud string
}

TokenData which can be accessed via the request context and provides the resolved information about the aud and the sub of the token

Jump to

Keyboard shortcuts

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