cidaasutils

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2021 License: MIT Imports: 16 Imported by: 0

README

Cidaas Utils

This library contains a few (unofficial) utility functions for working with the Cidaas API.

Features

  • Validate a JWT using the provided public JWKs from Cidaas.
  • Intercept http requests, validate token and attach to request context.
  • Use authentication_code and refresh_token flows.
  • Get and update user information.

Dependencies

The library depends on these libraries

  • github.com/MicahParks/keyfunc
  • github.com/dgrijalva/jwt-go

Usage

import (
  "log"
  "http"

  "github.com/inheaden/cidaasutils"
)

func main() {
  utils := cidaasutils.New(&cidaasutils.Options{BaseURL: "https://example.cidaas.com"})
  utils.Init()

  //...

  token, err := utils.ValidateJWT(jwtToken)
  if err != nil {
    log.Fatal(err)
  }
  log.Print(token)

  mux := http.NewServeMux()
  mux.Handle("/", utils.JWTInterceptor(yourHandler, WithRoles([]string{"ADMIN"})))
  http.ListenAndServe(":8000", mux)
}

Documentation

Index

Constants

View Source
const Version = "0.1.6"

Variables

View Source
var CidaasClaimKey = "CIDAAS_CLAIMS"

CidaasClaimKey Key used for storing the claims on the context

View Source
var NoResultError = errors.New("no results")
View Source
var TokenInvalidError = errors.New("token is invalid")

TokenInvalidError is returned if the given token is invalid

Functions

func IsTokenExpired

func IsTokenExpired(token *jwt.Token) bool

Types

type AccessTokenResult

type AccessTokenResult struct {
	Sub          string `json:"sub"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
}

type CidaasTokenClaims

type CidaasTokenClaims struct {
	Sub       string   `json:"sub,omitempty"`
	Email     string   `json:"email,omitempty"`
	Scopes    []string `json:"scopes,omitempty"`
	Roles     []string `json:"roles,omitempty"`
	ExpiresAt int64    `json:"exp,omitempty"`
	// Other contains all non-standard claims of the token
	Other jwt.MapClaims
}

CidaasTokenClaims describe the claims on a given token

func GetAuthContext

func GetAuthContext(ctx context.Context) *CidaasTokenClaims

GetAuthContext returns the CidaasTokenClaims from the request context if it exists otherwise nil.

func (*CidaasTokenClaims) Valid

func (c *CidaasTokenClaims) Valid() error

type CidaasUtils

type CidaasUtils struct {
	// contains filtered or unexported fields
}

CidaasUtils is the main struct for all utils functions.

func New

func New(options *Options) *CidaasUtils

New creates a new instance of the utils.

func (*CidaasUtils) AuthorizationCodeFlow

func (u *CidaasUtils) AuthorizationCodeFlow(code string, redirectURL string) (*AccessTokenResult, error)

AuthorizationCodeFlow completes the authorization flow using a code and a redirect URL. The redirect URL has to match the one used to create the authorization code.

func (*CidaasUtils) GetMyAccessToken

func (u *CidaasUtils) GetMyAccessToken() (*jwt.Token, error)

GetMyAccessToken returns the access token for the configured user. It will use the Admin credentials.

func (*CidaasUtils) GetUserProfileInternally

func (u *CidaasUtils) GetUserProfileInternally(sub string) (*UserInfo, error)

GetUserProfileInternally returns the internal user profile for the given sub id.

func (*CidaasUtils) Init

func (u *CidaasUtils) Init() error

Init initializes the JWKs and sets up a refresh interval.

func (*CidaasUtils) InitWithJWKs

func (u *CidaasUtils) InitWithJWKs(jwks *keyfunc.JWKS)

InitWithJWKs initializes the JWKs without needing to talk to a server.

func (*CidaasUtils) JWTInterceptor

func (u *CidaasUtils) JWTInterceptor(next http.Handler, options ...JWTInterceptorOption) http.Handler

JWTInterceptor parses and validates Bearer token in requests, compares them to the given option constraints and attaches the CidaasTokenClaims to the request context.

func (*CidaasUtils) RefreshTokenFlow

func (u *CidaasUtils) RefreshTokenFlow(refreshToken string) (*AccessTokenResult, error)

RefreshTokenFlow retrieves a new access token and refresh token.

func (*CidaasUtils) ToCidaasTokenClaims

func (u *CidaasUtils) ToCidaasTokenClaims(jwtToken *jwt.Token) (*CidaasTokenClaims, error)

ToCidaasClaims returns claims of the given token

func (*CidaasUtils) UpdateUserProfileInternally

func (u *CidaasUtils) UpdateUserProfileInternally(sub string, info *UserUpdateRequest) error

UpdateUserProfileInternally updates the user's profile.

func (*CidaasUtils) ValidateJWT

func (u *CidaasUtils) ValidateJWT(jwtToken string) (*jwt.Token, error)

ValidateJWT validates the given jwt and returns the parsed token.

type CustomField

type CustomField struct {
	Value interface{} `json:"value"`
}

type ICidaasUtils

type ICidaasUtils interface {
	Init() error
	ValidateJWT(token string) (*jwt.Token, error)
	GetUserProfileInternally(sub string) (*UserInfo, error)
	UpdateUserProfileInternally(sub string, info *UserUpdateRequest) error
	JWTInterceptor(next http.Handler, options ...JWTInterceptorOption) http.Handler
	GetMyAccessToken() (*jwt.Token, error)
	AuthorizationCodeFlow(code string, redirectURL string) (*AccessTokenResult, error)
	RefreshTokenFlow(refreshToken string) (*AccessTokenResult, error)
}

type JWTInterceptorOption

type JWTInterceptorOption func(option *jwtInterceptorOptions)

JWTInterceptorOption can be used to customize the Interceptor

func WithAuthorized

func WithAuthorized() JWTInterceptorOption

WithAuthorized allows only requests which contain a valid token

func WithRoles

func WithRoles(roles []string) JWTInterceptorOption

WithRoles allows only requests which contain a JWT with all of the provided roles.

func WithScopes

func WithScopes(scopes []string) JWTInterceptorOption

WithScopes allows only requests which contain a JWT with all of the provided scopes.

type Options

type Options struct {
	// This is the base url for communicating with Cidaas.
	// Usually something like https://your-company.cidaas.com
	BaseURL string

	// App credentials
	ClientID     string
	ClientSecret string

	// Credentials for an admin user (used to retrieve an access_token)
	AdminUsername string
	AdminPassword string

	// Interval how often the JWKs will be refreshed from Cidaas.
	// Default is one hour.
	RefreshInterval time.Duration
}

type RequestInit

type RequestInit struct {
	Path     string
	Token    string
	Method   string
	BodyForm *url.Values
	BodyJSON interface{}
	Context  context.Context
}

type SimpleStatusResponse

type SimpleStatusResponse struct {
	Success bool        `json:"success"`
	Status  int         `json:"status"`
	Data    interface{} `json:"data"`
}

type UserAccount

type UserAccount struct {
}

type UserIdentity

type UserIdentity struct {
	Sub          string `json:"sub"`
	Email        string `json:"email"`
	FamilyName   string `json:"family_name"`
	GivenName    string `json:"given_name"`
	MobileNumber string `json:"mobile_number"`
	Locale       string `json:"locale"`
	Provider     string `json:"provider"`
}

type UserInfo

type UserInfo struct {
	Identity     UserIdentity           `json:"identity"`
	UserAccount  UserAccount            `json:"userAccount"`
	Roles        []string               `json:"roles"`
	CustomFields map[string]CustomField `json:"customFields"`
}

type UserInfoResponse

type UserInfoResponse struct {
	Data UserInfo `json:"data"`
}

type UserUpdateRequest

type UserUpdateRequest struct {
	Email        *string                 `json:"email"`
	FamilyName   *string                 `json:"family_name"`
	GivenName    *string                 `json:"given_name"`
	MobileNumber *string                 `json:"mobile_number"`
	Provider     *string                 `json:"provider"`
	Locale       *string                 `json:"locale"`
	CustomFields *map[string]CustomField `json:"customFields"`
}

Jump to

Keyboard shortcuts

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