authorization

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2019 License: GPL-3.0 Imports: 7 Imported by: 0

README

go-jwt-tools

Golang authorization http middleware for Authorization headers

These are the important features on this package:

  • User: The object representation of who is doing the request and its permissions.
type User struct {
	AuthorizationValue string
	IsDummy            bool
	Permissions        Permissions
	UserID             []string
}

type Permissions interface {
	// CheckPermission returns the given Permissions for a given product and object. Returns the special Permissions applied on that object if any, and a boolean indicating if the user has the requested Permission. NOTE: Special Permissions returned can be filtered by the specials argument).
	CheckPermission(product string, object string, permission Permission, specials ...string) ([]string, bool)
	// ValidGroups returns all the groups and its Permissions that have any Permission for the given product and object.
	ValidGroups(product string, object string, permission Permission) map[string]struct{}
	// Returns all groups of a given type
	GetGroups(groupType string) []string
	// GetAllGroups returns the group hierarchy
	GetAllGroups() map[string]struct{}
	// GetGroupsByTypes returns a map indexed by group types, containing the list of groups of that type
	GetGroupsByTypes() map[string][]string
	// GetParents returns all the parent groups of a given group.
	GetParents(group string) map[string]interface{}
}

  • Parser: Who knows how to transform an authorization header into an User, this is what the different authorization techniques should implement.
type Parser interface {
	Parse(authHeader string) (*User, error)
}
  • Middleware: A middleware is a wrap to a http.Handler
func(h http.Handler) http.Handler

This concrete middleware requires a Parser that will be used to transform the Authorization header from http.Request into an User, and then put in the request context. To retrieve the User from the context, use the function:

func UserFromContext(ctx context.Context) (*User, bool)
Implementations

Implementation details can be found in these subpackages:

jwt

In this implementation, the Authorization headers must be Bearers (auth0 or other).

The jwt parser can be instantiated from:

type ParserConfig struct {
	PublicKey        string  
	AdminGroup       string  
	DummyToken       string  
	IgnoreExpiration bool    
	MemberIDClaim    []string
	GroupsClaim      []string
}
cache

Has a Parser implementation that uses a lru cache where the key is the Authorization header and the value is the User, it basically caches the Parsing process. Recommended when the parsing process is heavy.

How to use

First instance the desired Parser implementation, for instance, if we want our endpoint to understand of jwt bearers:

jwtParserConfig := jwt.ParserConfig{
		AdminGroup:       "admin",
		PublicKey:        "myKey",
		DummyToken:       "dummyToken",
		IgnoreExpiration: false,
		GroupsClaim:      []string{"https://xtg.com/iam", "https://travelgatex.com/iam"},
		MemberIDClaim:    []string{"https://xtg.com/member_id", "https://travelgatex.com/member_id"},
	}

jwtParser := jwt.NewParser(jwtParserConfig)

Then, if we want a cache layer to cache the jwt parsing process we can wrap the jwtParser with a cache parser:

size := 100
ttl := time.Minute
c, _ := cache.New(size, ttl)
cacheParser := authcache.NewParser(jwtParser, c)

Now that we have built the desired parser cacheParser, instance the middleware and use it to wrap your service handler:

middleware := authorization.Middleware(cacheParser)

var serviceHandler http.Handler // omitted code
serviceHandler = middleware(serviceHandler)

http.Handle("/foo", serviceHandler)

Remember that in order to obtain the User, you must retrieve it from the context.Context using the func UserFromContext

Documentation

Index

Constants

View Source
const ADDITIONAL = "a"
View Source
const AuthKey = key("authorization")
View Source
const ContextKey = key("permission")

ContextKey contains the key where the PermissionTree will be stored

View Source
const GROUP = "c"
View Source
const GROUPS = "g"
View Source
const GROUP_Permission = "grp"
View Source
const PRODUCTS = "p"
View Source
const TYPE = "t"

Variables

View Source
var ErrInvalidUser = errors.New("Invalid User")

Functions

func Authorize

func Authorize(inner http.Handler, c Config) http.Handler

func Middleware added in v1.2.0

func Middleware(p Parser) func(h http.Handler) http.Handler

Middleware creates a User from a Parser and puts it in the request context which can be later obtained by calling to UserFromContext() Errors returned from Parser are printed to the response body

Types

type Config added in v1.1.1

type Config struct {
	PublicKeyStr     string   `json:"public_key_str"`
	AdminGroup       string   `json:"admin_group"`
	MemberIDClaim    []string `json:"member_id_claim"`
	GroupsClaim      []string `json:"groups_claim"`
	DummyToken       string   `json:"dummy_token"`
	IgnoreExpiration bool     `json:"ignore_expiration"`
}

type GroupTree added in v1.1.1

type GroupTree struct {
	Type   string               // Group type
	Groups map[string]GroupTree // Group hierarchy tree
}

type Parser added in v1.2.0

type Parser interface {
	Parse(authHeader string) (*User, error)
}

Parser creates a User from an authorization header

type Permission added in v1.2.0

type Permission string
const (
	Create  Permission = "c"
	Update  Permission = "u"
	Delete  Permission = "d"
	Read    Permission = "r"
	Execute Permission = "x"
	Admin   Permission = "a"
)

type PermissionTable

type PermissionTable struct {
	Permissions map[string]map[string]map[Permission]map[string]struct{} //Product-->object-->Permission-->Groups
	IsAdmin     bool
	Bearer      string
	Groups      []map[string]GroupTree // Group hierarchy tree
	MemberID    []string               // Member identifier
}

func NewPermissionTable

func NewPermissionTable(jwt interface{}, memberId []string, bearer string, adminGroup string) *PermissionTable

func PermissionTableFromContext added in v1.1.1

func PermissionTableFromContext(ctx context.Context) (*PermissionTable, bool)

PermissionTableFromContext returns the permissionTable stored in a context

func (*PermissionTable) CheckPermission

func (t *PermissionTable) CheckPermission(product string, object string, per Permission, groups ...string) ([]string, bool)

Checks the user Permissions for a specified product and object Returns: Groups that have the requested Permissions

func (*PermissionTable) GetAllGroups

func (t *PermissionTable) GetAllGroups() map[string]struct{}

Return the group codes

func (*PermissionTable) GetGroups added in v1.1.1

func (t *PermissionTable) GetGroups(groupType string) []string

Returns all groups of a given type

func (*PermissionTable) GetGroupsByTypes added in v1.1.1

func (t *PermissionTable) GetGroupsByTypes() map[string][]string

Returns a map indexed by group types, containing the list of groups of that type

func (*PermissionTable) GetParents

func (t *PermissionTable) GetParents(group string) map[string]interface{}

Returns all the parents of a given group

func (*PermissionTable) ValidGroups

func (t *PermissionTable) ValidGroups(product string, object string, per Permission) map[string]struct{}

Return all the groups that have a Permissions into an object

type Permissions added in v1.2.0

type Permissions interface {
	// CheckPermission returns the given Permissions for a given product and object. Returns the special Permissions applied on that object if any, and a boolean indicating if the user has the requested Permission. NOTE: Special Permissions returned can be filtered by the specials argument).
	CheckPermission(product string, object string, permission Permission, specials ...string) ([]string, bool)
	// ValidGroups returns all the groups and its Permissions that have any Permission for the given product and object.
	ValidGroups(product string, object string, permission Permission) map[string]struct{}
	// Returns all groups of a given type
	GetGroups(groupType string) []string
	// GetAllGroups returns the group hierarchy
	GetAllGroups() map[string]struct{}
	// GetGroupsByTypes returns a map indexed by group types, containing the list of groups of that type
	GetGroupsByTypes() map[string][]string
	// GetParents returns all the parent groups of a given group.
	GetParents(group string) map[string]interface{}
}

type User added in v1.2.0

type User struct {
	// AuthorizationValue is the auth header value with which a user was created
	AuthorizationValue string
	IsDummy            bool
	FetchNeeded        bool
	Permissions        Permissions
	UserID             []string
}

User is a parsed Authorization header

func UserFromContext added in v1.2.0

func UserFromContext(ctx context.Context) (*User, bool)

UserFromContext returns the User stored in a context

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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