auth

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

README

auth-go-sdk

Go Reference

用于集成权限验证的开发包

支持的加密方式

RS256,RS384,RS512 #(使用RSA)
ES256,ES384,ES512 #(使用ECDSA)

默认为ES256

秘钥的生成

ECDSA
# 1. 生成 ec 算法的私钥,使用 prime256v1 算法,密钥长度 256 位。(强度大于 2048 位的 RSA 密钥)
openssl ecparam -genkey -name prime256v1 -noout -out ecc-private-key.pem
# 2. 通过密钥生成公钥
openssl ec -in ecc-private-key.pem -pubout -out ecc-public-key.pem
RSA
# 1. 生成 2048 位(不是 256 位)的 RSA 密钥
openssl genrsa -out rsa-private-key.pem 2048
# 2. 通过密钥生成公钥
openssl rsa -in rsa-private-key.pem -pubout -out rsa-public-key.pem

快速开始

安装
go get -u github.com/Macrow/auth-go-sdk
RSA
  • 请使用PKCS8格式生成RSA秘钥对,长度至少为2048
AES
  • AES加密采用128位AES/ECB/PKCS5Padding,不使用偏移量,最后用Base64输出
客户端id要求
  • 不能携带@符号

Documentation

Index

Constants

View Source
const (
	CodeSuccess              = 0
	DefaultCachePrefix       = "Jwt"
	DefaultCacheSplitter     = "::"
	DefaultIssuer            = "auth-go-sdk"
	DefaultHeaderRandomKey   = "Random-Key"
	DefaultHeaderAccessCode  = "Access-Code"
	DefaultHeaderUserToken   = "Authorization"
	DefaultHeaderClientToken = "HttpClient-Authorization"
	DefaultHeaderSchema      = "Bearer"
	DefaultMetaBy            = "id"
	DefaultAlgorithm         = "ES256"

	JwtTokenClaimsId          = "id"
	JwtTokenClaimsName        = "name"
	JwtTokenClaimsKind        = "kind"
	JwtTokenClaimsDeviceId    = "did"
	JwtTokenClaimsIssuer      = "iss"
	JwtTokenClaimsIssueAt     = "iat"
	JwtTokenClaimsExpireAt    = "exp"
	ClientIdAndSecretSplitter = "@"
	DidAndIatJoiner           = ":"

	UrlPostCheckAuth             = "/current/jwt"
	UrlPostCheckPermByCode       = "/current/check-operation"
	UrlPostCheckPermByAction     = "/current/check-action"
	UrlPostCheckClientAuth       = "/client/validate"
	UrlPostCheckClientPermByCode = "/client/check-operation"

	KeySkipAuthCheck = "__SkipAuthCheck__"
	KeyJwtUser       = "__JwtUser__"
	KeyCustomAuth    = "__CustomAuth__"
	KeyCustomPerm    = "__CustomPerm__"
	KeyClientId      = "__ClientId__"
	KeyMetaBy        = "__MetaBy__"

	TraceId = "request-trace-id"
)
View Source
const (
	MsgInternalError         = "服务内部错误"
	MsgAuthServerFail        = "访问鉴权服务失败"
	MsgAccessCodeEmpty       = "未提供访问码"
	MsgRandomKeyEmpty        = "未提供随机码"
	MsgUserTokenEmpty        = "未提供用户令牌"
	MsgClientTokenEmpty      = "未提供客户端令牌"
	MsgClientIdOrSecretEmpty = "未提供客户端Id和秘钥"
	MsgClientTokenFail       = "客户端验证失败"
	MsgJwtErrFormat          = "令牌格式错误"
	MsgJwtErrVersion         = "令牌版本错误"
	MsgNoResult              = "解析返回结果错误"
	MsgRateLimit             = "访问过于频繁"
	MsgAuthFail              = "身份验证失败"
	MsgPermFail              = "权限验证失败"
	MsgAESKeyError           = "加密key必须为16位"
	MsgEncryptFail           = "加密身份信息失败"
	MsgDecryptFail           = "身份信息校验失败"
	MsgEmptyContent          = "加解密内容为空"
)

Variables

View Source
var (
	ErrInternalError         = errors.New(MsgInternalError)
	ErrAuthServerFail        = errors.New(MsgAuthServerFail)
	ErrAccessCodeEmpty       = errors.New(MsgAccessCodeEmpty)
	ErrRandomKeyEmpty        = errors.New(MsgRandomKeyEmpty)
	ErrUserTokenEmpty        = errors.New(MsgUserTokenEmpty)
	ErrClientTokenEmpty      = errors.New(MsgClientTokenEmpty)
	ErrClientIdOrSecretEmpty = errors.New(MsgClientIdOrSecretEmpty)
	ErrClientTokenFail       = errors.New(MsgClientTokenFail)
	ErrJwtErrFormat          = errors.New(MsgJwtErrFormat)
	ErrJwtErrVersion         = errors.New(MsgJwtErrVersion)
	ErrNoResult              = errors.New(MsgNoResult)
	ErrRateLimit             = errors.New(MsgRateLimit)
	ErrAuthFail              = errors.New(MsgAuthFail)
	ErrPermFail              = errors.New(MsgPermFail)
	ErrAESKeyFail            = errors.New(MsgAESKeyError)
	ErrEncryptFail           = errors.New(MsgEncryptFail)
	ErrDecryptFail           = errors.New(MsgDecryptFail)
	ErrEmptyContent          = errors.New(MsgEmptyContent)
)

Functions

func AesEcbDecrypt added in v1.2.0

func AesEcbDecrypt(plainText, secretKey []byte) (cipherText []byte, err error)

func AesEcbDecryptByBase64 added in v1.2.0

func AesEcbDecryptByBase64(cipherTextBase64 string, key []byte) (plainText []byte, err error)

func AesEcbEncrypt added in v1.2.0

func AesEcbEncrypt(plainText, secretKey []byte) (cipherText []byte, err error)

func AesEcbEncryptBase64 added in v1.2.0

func AesEcbEncryptBase64(plainText, key []byte) (cipherTextBase64 string, err error)

func ExtractAccessCode added in v1.1.0

func ExtractAccessCode(f GetHeaderFun, header string, encryptContent bool, aesUtil *AesUtil, logger logr.Logger) (string, error)

func ExtractClientInfoAndToken

func ExtractClientInfoAndToken(f GetHeaderFun, header, headerSchema string, encryptContent bool, aesUtil *AesUtil, logger logr.Logger) (clientId string, clientSecret string, schemaAndToken string, err error)

func ExtractRandomKey added in v1.1.0

func ExtractRandomKey(f GetHeaderFun, header string) (string, error)

func ExtractUserToken

func ExtractUserToken(fun GetHeaderFun, header, headerSchema string) (string, error)

func GenerateClientToken

func GenerateClientToken(clientId string, clientSecret string, aesUtil *AesUtil) (string, error)

func GenerateRandomKey

func GenerateRandomKey() string

func GetClientId

func GetClientId(f GetValFunc) interface{}

func GetCustomAuth

func GetCustomAuth(f GetValFunc) interface{}

func GetCustomPerm

func GetCustomPerm(f GetValFunc) interface{}

func GetMetaBy

func GetMetaBy(f GetValFunc) string

func GetNonEmptyValue

func GetNonEmptyValue(val string) string

func GetNonEmptyValueWithBackup

func GetNonEmptyValueWithBackup(val string, backup string) string

func GetSkipAuthCheck

func GetSkipAuthCheck(f GetValFunc) bool

func PKCS5Padding added in v1.2.0

func PKCS5Padding(plainText []byte, blockSize int) []byte

func PKCS5UnPadding added in v1.2.0

func PKCS5UnPadding(plainText []byte, blockSize int) ([]byte, error)

func ParseClientToken

func ParseClientToken(clientToken string, encryptContent bool, aesUtil *AesUtil, logger logr.Logger) (clientId string, clientSecret string, err error)

func SetClientId

func SetClientId(clientId string, f SetValFunc)

func SetCustomAuth

func SetCustomAuth(customAuth interface{}, f SetValFunc)

func SetCustomPerm

func SetCustomPerm(customAuth interface{}, f SetValFunc)

func SetJwtUser

func SetJwtUser(jwtUser *JwtUser, f SetValFunc)

func SetMetaBy

func SetMetaBy(metaBy string, f SetValFunc)

func SetSkipAuthCheck

func SetSkipAuthCheck(skip bool, f SetValFunc)

Types

type AccessCode

type AccessCode struct {
	Enable             bool
	SkipUserTokenCheck bool
	Header             string
	EncryptContent     bool
}

type AesUtil added in v1.2.0

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

AesUtil AES加密采用128位AES/ECB/PKCS5Padding,不使用偏移量,最后用Base64输出

func NewAesUtil added in v1.2.0

func NewAesUtil(key string) *AesUtil

func (*AesUtil) CryptBlocks added in v1.2.0

func (a *AesUtil) CryptBlocks(block cipher.BlockMode, dist, src []byte, errCatch error)

type Auditing

type Auditing struct {
	MetaBy string
}

type CheckAuthResult

type CheckAuthResult struct {
	SkippedAuthCheck bool        `json:"skippedAuthCheck"`
	User             *JwtUser    `json:"user"`
	CustomAuth       interface{} `json:"customAuth"`
}

type CheckClientAuthResult

type CheckClientAuthResult struct {
	ClientAuthOk bool `json:"clientAuthOk"`
}

type CheckClientPermResult

type CheckClientPermResult struct {
	ClientPermOk bool `json:"clientPermOk"`
}

type CheckPermResult

type CheckPermResult struct {
	SkippedAuthCheck bool        `json:"skippedAuthCheck"`
	User             *JwtUser    `json:"user"`
	CustomAuth       interface{} `json:"customAuth"`
	CustomPerm       interface{} `json:"customPerm"`
}

type Client

type Client struct {
	Id                string
	Secret            string
	EnableIdAndSecret bool
	AccessCode        string
	Header            string
	HeaderSchema      string
	EncryptContent    bool
}

type ClientOption

type ClientOption func(*HttpClient)

func WithAccessCodeConfig

func WithAccessCodeConfig(config AccessCode) ClientOption

func WithAuditingConfig

func WithAuditingConfig(config Auditing) ClientOption

func WithClientConfig

func WithClientConfig(config Client) ClientOption

func WithHttpClientLogger added in v1.2.0

func WithHttpClientLogger(logger logr.Logger) ClientOption

func WithRandomKeyConfig

func WithRandomKeyConfig(config RandomKey) ClientOption

func WithUserConfig

func WithUserConfig(config User) ClientOption

type GetHeaderFun

type GetHeaderFun = func(key string) string

type GetValFunc

type GetValFunc = func(Key string) interface{}

type HttpClient

type HttpClient struct {
	Config  *HttpClientConfig
	Agent   *req.Client
	AesUtil *AesUtil
	// contains filtered or unexported fields
}

func NewHttpClient

func NewHttpClient(AuthServiceBaseUrl string, CurrentServiceName string, aesKey string, options ...ClientOption) *HttpClient

func (*HttpClient) CheckAuth

func (c *HttpClient) CheckAuth(f GetHeaderFun, fulfillCustomAuth bool) (*CheckAuthResult, error)

func (*HttpClient) CheckClientAuth

func (c *HttpClient) CheckClientAuth(f GetHeaderFun) (*CheckClientAuthResult, error)

func (*HttpClient) CheckClientPermByCode

func (c *HttpClient) CheckClientPermByCode(f GetHeaderFun, code string) (*CheckClientPermResult, error)

func (*HttpClient) CheckPermByAction

func (c *HttpClient) CheckPermByAction(f GetHeaderFun, service string, method string, path string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (*CheckPermResult, error)

func (*HttpClient) CheckPermByCode

func (c *HttpClient) CheckPermByCode(f GetHeaderFun, code string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (*CheckPermResult, error)

func (*HttpClient) ClientRequest added in v1.1.0

func (c *HttpClient) ClientRequest(traceId string, urlPath string, httpMethod string, queryParam map[string]any, formData map[string]any) (any, error)

type HttpClientConfig

type HttpClientConfig struct {
	Service
	AccessCode
	RandomKey
	User
	Client
	Auditing
}

type HttpResponse

type HttpResponse[T Result] struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Success bool   `json:"success"`
	Result  *T     `json:"result"`
}

type HttpResult added in v1.1.0

type HttpResult struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Success bool   `json:"success"`
	Result  any    `json:"result"`
}

type IAuthCheck

type IAuthCheck interface {
	IsAccessCodeOk(ctx context.Context, code string) (bool, error)
	IsRandomKeyOk(ctx context.Context, key string) (bool, error)
	CheckAuth(ctx context.Context, userToken string, fulfillCustomAuth bool) (*CheckAuthResult, error)
	CheckPermByCode(ctx context.Context, userToken string, code string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (*CheckPermResult, error)
	CheckPermByAction(ctx context.Context, userToken string, service string, method string, path string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (CheckPermResult, error)
	CheckClientAuth(ctx context.Context, clientId string, clientSecret string) (*CheckClientAuthResult, error)
	CheckClientPermByCode(ctx context.Context, clientId string, clientSecret string, code string) (*CheckClientPermResult, error)
}

IAuthCheck 实现本地验证服务

type IAuthClient

type IAuthClient interface {
	CheckAuth(f GetHeaderFun, fulfillCustomAuth bool) (*CheckAuthResult, error)
	CheckPermByCode(f GetHeaderFun, code string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (*CheckPermResult, error)
	CheckPermByAction(f GetHeaderFun, service string, method string, path string, fulfillJwt bool, fulfillCustomAuth bool, fulfillCustomPerm bool) (*CheckPermResult, error)
	CheckClientAuth(f GetHeaderFun) (*CheckClientAuthResult, error)
	CheckClientPermByCode(f GetHeaderFun, code string) (*CheckClientPermResult, error)
}

IAuthClient 实现远程调用验证,所有方法都不抛出异常,如果权限检查失败,jwtUser返回nil

type Jwt

type Jwt struct {
	Prefix              string
	CacheSplitter       string
	Issuer              string
	ExpireInMinutes     int
	Algorithm           string
	PublicKey           []byte
	PrivateKey          []byte
	DebugMode           bool
	AutoRefreshToken    bool
	AutoExtendInMinutes int
}

type JwtUser

type JwtUser struct {
	RawJwtUser
	Token string `json:"token"` // 令牌字符串
}

func GetJwtUser

func GetJwtUser(f GetValFunc) *JwtUser

type JwtUtilConfig

type JwtUtilConfig struct {
	Redis
	Jwt
}

type JwtUtilOption

type JwtUtilOption func(util *RedisJwtUtil)

func WithJwtConfig

func WithJwtConfig(config Jwt) JwtUtilOption

func WithRedisConfig

func WithRedisConfig(config Redis) JwtUtilOption

type LocalAccessCode

type LocalAccessCode struct {
	Enable         bool
	Header         string
	EncryptContent bool
}

type LocalAuditing

type LocalAuditing struct {
	MetaBy string
}

type LocalAuthChecker

type LocalAuthChecker struct {
	Config  *LocalAuthCheckerConfig
	AesUtil *AesUtil
	// contains filtered or unexported fields
}

func NewLocalAuthChecker

func NewLocalAuthChecker(aesKey string, options ...LocalCheckerOption) *LocalAuthChecker

func (*LocalAuthChecker) ExtractAccessCode

func (c *LocalAuthChecker) ExtractAccessCode(f GetHeaderFun) (string, error)

func (*LocalAuthChecker) ExtractClientInfoAndToken

func (c *LocalAuthChecker) ExtractClientInfoAndToken(f GetHeaderFun) (string, string, string, error)

func (*LocalAuthChecker) ExtractRandomKey

func (c *LocalAuthChecker) ExtractRandomKey(f GetHeaderFun) (string, error)

func (*LocalAuthChecker) ExtractUserToken

func (c *LocalAuthChecker) ExtractUserToken(f GetHeaderFun) (string, error)

type LocalCheckerOption

type LocalCheckerOption func(checker *LocalAuthChecker)

func WithAuthCheckerLogger added in v1.2.0

func WithAuthCheckerLogger(logger logr.Logger) LocalCheckerOption

func WithLocalAccessCodeConfig

func WithLocalAccessCodeConfig(config LocalAccessCode) LocalCheckerOption

func WithLocalAuditingConfig

func WithLocalAuditingConfig(config LocalAuditing) LocalCheckerOption

func WithLocalClientConfig

func WithLocalClientConfig(config LocalClient) LocalCheckerOption

func WithLocalRandomKeyConfig

func WithLocalRandomKeyConfig(config LocalRandomKey) LocalCheckerOption

func WithLocalUserConfig

func WithLocalUserConfig(config LocalUser) LocalCheckerOption

type LocalClient

type LocalClient struct {
	EnableIdAndSecret bool
	Header            string
	HeaderSchema      string
	EncryptContent    bool
}

type LocalRandomKey

type LocalRandomKey struct {
	Enable bool
	Header string
}

type LocalUser

type LocalUser struct {
	Header       string
	HeaderSchema string
}

type PagedResult added in v1.1.0

type PagedResult struct {
	Items    []any `json:"items"`
	Total    int   `json:"total"`
	Page     int   `json:"page"`
	PageSize int   `json:"pageSize"`
}

type RandomKey

type RandomKey struct {
	Enable bool
	Header string
}

type RawJwtUser

type RawJwtUser struct {
	Id   string  `json:"id"`   // 用户id
	Name string  `json:"name"` // 用户登录名
	Kind string  `json:"kind"` // 用户类型
	Did  string  `json:"did"`  // 设备id
	Iss  string  `json:"iss"`  // 签发者
	Iat  float64 `json:"iat"`  // 签发时间
	Exp  float64 `json:"exp"`  // 过期时间
}

type Redis

type Redis struct {
	Address  string
	Db       int
	Password string
}

type RedisJwtUtil

type RedisJwtUtil struct {
	Ctx                context.Context
	Config             JwtUtilConfig
	RedisClient        *redis.Client
	RedisClusterClient *redis.ClusterClient
	Method             jwt.SigningMethod
	PublicKey          interface{}
	PrivateKey         interface{}
	RateLimiter        *redis_rate.Limiter
}

func NewRedisJwtUtil

func NewRedisJwtUtil(ctx context.Context, options ...JwtUtilOption) *RedisJwtUtil

func (*RedisJwtUtil) CheckJwtIsInCache

func (j *RedisJwtUtil) CheckJwtIsInCache(jwtUser *JwtUser) bool

func (*RedisJwtUtil) ClearRedisCachesByKey

func (j *RedisJwtUtil) ClearRedisCachesByKey(key string)

func (*RedisJwtUtil) ClearRedisCachesByKeyPattern

func (j *RedisJwtUtil) ClearRedisCachesByKeyPattern(keyPattern string)

func (*RedisJwtUtil) DelJwtByUserId

func (j *RedisJwtUtil) DelJwtByUserId(id string)

func (*RedisJwtUtil) DelJwtByUserIdAndDeviceId

func (j *RedisJwtUtil) DelJwtByUserIdAndDeviceId(id, did string)

func (*RedisJwtUtil) DelJwtByUserIdAndDeviceIdAndIat

func (j *RedisJwtUtil) DelJwtByUserIdAndDeviceIdAndIat(id, did string, iat float64)

func (*RedisJwtUtil) GenerateJwt

func (j *RedisJwtUtil) GenerateJwt(id, username, kind, deviceId string, issueAt float64, expireAt float64) (jwtUser *JwtUser, err error)

func (*RedisJwtUtil) GetObjInRedis

func (j *RedisJwtUtil) GetObjInRedis(key string) interface{}

func (*RedisJwtUtil) GetUserDidJwtCacheKeyPrefix

func (j *RedisJwtUtil) GetUserDidJwtCacheKeyPrefix(id, did string) string

func (*RedisJwtUtil) GetUserJwtCacheKey

func (j *RedisJwtUtil) GetUserJwtCacheKey(id, did string, iat float64) string

func (*RedisJwtUtil) GetUserJwtCacheKeyPrefix

func (j *RedisJwtUtil) GetUserJwtCacheKeyPrefix(id string) string

func (*RedisJwtUtil) IsRedisCluster

func (j *RedisJwtUtil) IsRedisCluster() bool

func (*RedisJwtUtil) RateLimitByMinute

func (j *RedisJwtUtil) RateLimitByMinute(key string, timesPerMinute int) error

func (*RedisJwtUtil) RateLimitBySecond

func (j *RedisJwtUtil) RateLimitBySecond(key string, timesPerSecond int) error

func (*RedisJwtUtil) SetJwtUser

func (j *RedisJwtUtil) SetJwtUser(jwtUser *JwtUser)

func (*RedisJwtUtil) SetObjInRedis

func (j *RedisJwtUtil) SetObjInRedis(key string, obj interface{}, expiredInMinutes int)

func (*RedisJwtUtil) SignJwtAndSaveToCache

func (j *RedisJwtUtil) SignJwtAndSaveToCache(id, name, kind, did string) *JwtUser

func (*RedisJwtUtil) ValidateJwt

func (j *RedisJwtUtil) ValidateJwt(tokenString string) (*JwtUser, error)

type Service

type Service struct {
	AuthServiceBaseUrl string
	CurrentServiceName string
	EncryptKey         string
	EnableTraceLog     bool
}

type SetValFunc

type SetValFunc = func(key string, val interface{})

type User

type User struct {
	Header       string
	HeaderSchema string
}

Jump to

Keyboard shortcuts

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