func validateTokenClaims(claims jwt.MapClaims, allowedRoles []string) error {
	if claims["authorities"] == nil {
		log.Info("Invalid token A")
		return errors.New(InvalidToken)
	}
	err := ValidateRole(claims, allowedRoles)
	if err != nil {
		return err
	}
	if claims["userId"] == nil {
		log.Info("Invalid token UI")
		return errors.New(InvalidToken)
	}
	if claims["user_name"] == nil {
		log.Info("Invalid token UN")
		return errors.New(InvalidToken)
	}
	err = claims.Valid()
	if err != nil {
		log.Info("token expired")
		return errors.New(InvalidToken)
	}
	return nil
}
Validate token claims
package util
import (
	"crypto/tls"
	"errors"
	"k8splugin/conf"
	"math/rand"
	"os"
	"reflect"
	"regexp"
	"strings"
	"github.com/dgrijalva/jwt-go"
	"github.com/go-playground/validator/v10"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)
var (
	jwtPublicKey = os.Getenv("JWT_PUBLIC_KEY")
)
const (
	minPasswordSize = 8
	maxPasswordSize = 16
	specialCharRegex string = `['~!@#$%^&()-_=+\|[{}\];:'",<.>/?]`
	singleDigitRegex string = `\d`
	lowerCaseRegex string = `[a-z]`
	upperCaseRegex string = `[A-Z]`
	maxPasswordCount = 2
	Default string = "default"
	DriverName string = "postgres"
	InvalidToken string = "invalid token"
	CannotReceivePackage = "Cannot receive package metadata."
	FilePerm = 0750
	HostIpIsInvalid = "hostIp is invalid"
	TenantIdIsInvalid = "tenantId is invalid"
	AKIsInvalid = "ak is invalid"
	SKIsInvalid = "sk is invalid"
	PackageIdIsInvalid = "packageId is invalid"
	TenantIsInvalid = "hostIp is invalid"
	AccssTokenIsInvalid = "accessToken is invalid"
	Success = "Success"
	Failure = "Failure"
	ActionConfig = "Unable to initialize action config"
	HelmDriver = ""
	DeployType = "helm"
	AppInsId = "app_ins_id"
	AppPkgId = "app_pkg_id"
	maxHostNameLen = 253
	maxAkLen = 20
	maxSkLen = 64
	MaxIPVal = 255
	ServerNameRegex string = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`
	Forbidden string = "forbidden"
	MaxConfigFile              = 5242880
	MaxPackageFile             = 536870912
	FailedToDispRecvMsg    = "failed to display receive msg"
	FailedToValInputParams = "failed to validate input parameters"
	FailedToGetClient      = "failed to get client"
	AppRecordDoesNotExit   = "app info record does not exist in database"
	AppPkgRecordDoesNotExit   = "app package record does not exist in database"
	WorkloadEvents       = "WorkloadEvents"
	Query                  = "Query"
	QueryKPI               = "QueryKPI"
	Instantiate            = "Instantiate"
	Terminate              = "Terminate"
	UploadConfig           = "UploadConfig"
	UploadPackage          = "UploadPackage"
	RemoveConfig           = "RemoveConfig"
	DeletePackage          = "DeletePackage"
	QueryPackageStatus    = "QueryPackageStatus"
	MecmTenantRole         = "ROLE_MECM_TENANT"
	MecmAdminRole          = "ROLE_MECM_ADMIN"
	MecmGuestRole          = "ROLE_MECM_GUEST"
	TooManyFile int = 1024
	TooBig = 0x6400000
	SingleFileTooBig = 0x6400000
	RpcName = " RpcName ["
	Pod = "Pod"
	Deployment = "Deployment"
	Service = "Service"
	FailedToJsonMarshal = "Failed to json marshal"
	AppInsIdValid = "appInsId is invalid"
	FailedToDelAppPkg = "failed to delete application package"
	MaxSize = 20
	MaxBackups = 50
	MaxAge = 30
	Compress = true
	KubeConfigNotFound = "kubeconfig corresponding to given edge can't be found"
)
var cipherSuiteMap = map[string]uint16{
	"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
}
// Validate password
func ValidatePassword(password *[]byte) (bool, error) {
	if len(*password) >= minPasswordSize && len(*password) <= maxPasswordSize {
		// password must satisfy any two conditions
		pwdValidCount := getPasswordValidCount(password)
		if pwdValidCount < maxPasswordCount {
			return false, errors.New("password must contain at least two types of the either one lowercase" +
				" character, one uppercase character, one digit or one special character")
		}
	} else {
		return false, errors.New("password must have minimum length of 8 and maximum of 16")
	}
	return true, nil
}
// To get password valid count
func getPasswordValidCount(password *[]byte) int {
	var pwdValidCount = 0
	pwdIsValid, err := regexp.Match(singleDigitRegex, *password)
	if pwdIsValid && err == nil {
		pwdValidCount++
	}
	pwdIsValid, err = regexp.Match(lowerCaseRegex, *password)
	if pwdIsValid && err == nil {
		pwdValidCount++
	}
	pwdIsValid, err = regexp.Match(upperCaseRegex, *password)
	if pwdIsValid && err == nil {
		pwdValidCount++
	}
	// space validation for password complexity is not added
	// as jwt decrypt fails if space is included in password
	pwdIsValid, err = regexp.Match(specialCharRegex, *password)
	if pwdIsValid && err == nil {
		pwdValidCount++
	}
	return pwdValidCount
}
// Validate db parameters
func ValidateDbParams(dbPwd string) (bool, error) {
	dbPwdBytes := []byte(dbPwd)
	dbPwdIsValid, validateDbPwdErr := ValidatePassword(&dbPwdBytes)
	if validateDbPwdErr != nil || !dbPwdIsValid {
		return dbPwdIsValid, validateDbPwdErr
	}
	return true, nil
}
// Clear byte array from memory
func ClearByteArray(data []byte) {
	for i := 0; i < len(data); i++ {
		data[i] = 0
	}
}
// Validate access token
func ValidateAccessToken(accessToken string, allowedRoles []string) error {
	if accessToken == "" {
		return nil
	}
	claims := jwt.MapClaims{}
	token, err := jwt.ParseWithClaims(accessToken, claims, func(_ *jwt.Token) (interface{}, error) {
		return jwtPublicKey, nil
	})
	if token != nil && !token.Valid {
		err := validateTokenClaims(claims, allowedRoles)
		if err != nil {
			return err
		}
	} else if er, ok := err.(*jwt.ValidationError); ok {
		if er.Errors&jwt.ValidationErrorMalformed != 0 {
			log.Error("Invalid token")
			return errors.New(InvalidToken)
		} else if er.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
			log.Error("token expired or inactive")
			return errors.New("token expired or inactive")
		} else {
			log.Error("Couldn't handle this token: ", err)
			return errors.New(err.Error())
		}
	} else {
		log.Error("Couldn't handle this token: ", err)
		return errors.New(err.Error())
	}
	log.Debug("Token validated successfully")
	return nil
}