Documentation
¶
Overview ¶
Application scenarios: - Define the business-facing JWT authentication contract used by handlers and services. - Keep JWT signing, verification, and default-claims construction provider-neutral. - Separate user/business JWT semantics from service-to-service authentication semantics.
适用场景: - 定义 handler 和 service 直接使用的业务侧 JWT 认证契约。 - 在 provider 中立的前提下统一 JWT 签发、校验和默认 claims 构建语义。 - 将用户/业务 JWT 语义与服务间身份认证语义分离开来。
Application scenarios: - Propagate JWT-derived identity information through request-scoped contexts. - Let middleware, handlers, and services share one consistent access path for claims and subject identity. - Keep security-related context keys private to avoid cross-package collisions.
适用场景: - 在请求级 context 中透传由 JWT 解析出的身份信息。 - 让 middleware、handler 和 service 共享统一的 claims 与主体身份读取路径。 - 将安全相关 context key 保持为私有,避免跨包冲突。
Package security provides the minimal authorization contract for gorp framework.
Package security provides the minimal authentication and security contracts for gorp framework.
Application scenarios: - Define service-to-service authentication contracts used by microservice runtime flows. - Support token-based, mTLS-based, and peer-certificate-based identity verification. - Keep service-auth provider creation and config models independent from concrete implementations.
适用场景: - 定义微服务运行时流程使用的服务间身份认证契约。 - 支持基于 token、mTLS 和对端证书的身份校验方式。 - 让服务鉴权 provider 的创建和配置模型不依赖具体实现。
Application scenarios: - Propagate service-auth credentials (Authorization header, X-Service-Token) through request contexts. - Give service-auth middleware, interceptors, and authenticators one consistent, collision-free access path. - Replace fragile string context keys with typed keys so cross-package contracts are compile-checked.
适用场景: - 在请求 context 中透传服务认证凭据(Authorization 头、X-Service-Token)。 - 让 service-auth middleware、interceptor 和 authenticator 共享统一的、无冲突的访问路径。 - 用类型化 key 取代脆弱的字符串 context key,让跨包契约受编译期约束。
Application scenarios: - Propagate authenticated service identity through request-scoped contexts. - Let service-auth middleware, handlers, and downstream services share one consistent identity access path. - Keep service-identity context keys private and collision-free.
适用场景: - 在请求级 context 中透传已认证的服务身份。 - 让服务鉴权 middleware、handler 和下游 service 共享统一的身份读取路径。 - 保持服务身份相关 context key 私有且避免冲突。
Index ¶
- Constants
- func AuthorizationFrom(ctx context.Context) string
- func FromSubjectIDContext(ctx context.Context) (int64, bool)
- func FromSubjectTypeContext(ctx context.Context) (string, bool)
- func NewJWTClaimsContext(ctx context.Context, claims *JWTClaims) context.Context
- func NewServiceIdentityContext(ctx context.Context, identity *ServiceIdentity) context.Context
- func NewSubjectIDContext(ctx context.Context, subjectID int64) context.Context
- func NewSubjectTypeContext(ctx context.Context, subjectType string) context.Context
- func ServiceTokenFrom(ctx context.Context) string
- func TLSStateFrom(ctx context.Context) *tls.ConnectionState
- func WithAuthorization(ctx context.Context, value string) context.Context
- func WithServiceToken(ctx context.Context, value string) context.Context
- func WithTLSState(ctx context.Context, state *tls.ConnectionState) context.Context
- type Authorizer
- type CaptchaStore
- type Container
- type JWTClaims
- type JWTService
- type ServiceAuthConfig
- type ServiceAuthProvider
- type ServiceAuthenticator
- type ServiceIdentity
- type ServicePeerCertificateAuthenticator
- type ServiceProvider
- type ServiceTokenIssuer
- type ServiceTokenVerifier
- type TLSCertificateLoader
Constants ¶
const ( ServiceAuthKey = "framework.service.auth" ServiceIdentityKey = "framework.service.identity" )
const ( // AuthJWTKey is the container key for the business JWT service. // // AuthJWTKey 是业务侧 JWT 服务的容器键。 AuthJWTKey = "framework.auth.jwt" )
const AuthorizerKey = "framework.security.authorizer"
AuthorizerKey is the container key for the authorizer capability.
const CaptchaStoreKey = "framework.security.captcha_store"
CaptchaStoreKey is the container key for the captcha store capability.
const ContextJWTClaimsKey = "framework.jwt.claims"
ContextJWTClaimsKey 是 JWT claims 在 Gin context 中的存储键。 统一定义在 securitycontract 包,避免 middleware 和 jwt provider 之间的循环依赖。
ContextJWTClaimsKey is the key for JWT claims in Gin context. Defined in securitycontract to avoid circular dependencies between middleware and jwt provider.
const DefaultCasbinRBACModelText = `` /* 288-byte string literal not displayed */
DefaultCasbinRBACModelText is the embedded standard RBAC model for Casbin. It provides a zero-file-dependency, fail-safe model so applications never crash when external configuration files are missing or paths vary across environments.
DefaultCasbinRBACModelText 是嵌入式的标准 Casbin RBAC 模型定义。 提供零文件依赖的兜底能力,避免因外部配置文件缺失或相对路径不一致导致进程崩溃。
Variables ¶
This section is empty.
Functions ¶
func AuthorizationFrom ¶ added in v0.2.0
AuthorizationFrom retrieves the raw Authorization header value from the context.
AuthorizationFrom 从 context 中读取原始 Authorization 头值。
func FromSubjectIDContext ¶
FromSubjectIDContext reads the authenticated subject ID from the context.
FromSubjectIDContext 从 context 中读取认证主体 ID。
func FromSubjectTypeContext ¶
FromSubjectTypeContext reads the authenticated subject type from the context.
FromSubjectTypeContext 从 context 中读取认证主体类型。
func NewJWTClaimsContext ¶
NewJWTClaimsContext writes JWT claims into the context.
NewJWTClaimsContext 将 JWT claims 写入 context。
func NewServiceIdentityContext ¶
func NewServiceIdentityContext(ctx context.Context, identity *ServiceIdentity) context.Context
NewServiceIdentityContext stores service identity in context.
NewServiceIdentityContext 将服务身份写入 context。
func NewSubjectIDContext ¶
NewSubjectIDContext writes the authenticated subject ID into the context.
NewSubjectIDContext 将认证主体 ID 写入 context。
func NewSubjectTypeContext ¶
NewSubjectTypeContext writes the authenticated subject type into the context.
NewSubjectTypeContext 将认证主体类型写入 context。
func ServiceTokenFrom ¶ added in v0.2.0
ServiceTokenFrom retrieves the raw X-Service-Token header value from the context.
ServiceTokenFrom 从 context 中读取原始 X-Service-Token 头值。
func TLSStateFrom ¶ added in v0.2.0
func TLSStateFrom(ctx context.Context) *tls.ConnectionState
TLSStateFrom retrieves the peer TLS connection state from the context. Returns nil when the connection is not TLS or the state was not injected.
TLSStateFrom 从 context 中读取对端 TLS 连接状态。 连接非 TLS 或未注入时返回 nil。
func WithAuthorization ¶ added in v0.2.0
WithAuthorization stores the raw Authorization header value into the context.
WithAuthorization 将原始 Authorization 头值写入 context。
func WithServiceToken ¶ added in v0.2.0
WithServiceToken stores the raw X-Service-Token header value into the context.
WithServiceToken 将原始 X-Service-Token 头值写入 context。
func WithTLSState ¶ added in v0.2.0
WithTLSState stores the peer TLS connection state into the context. The transport layer (HTTP/gin or gRPC) injects this so mTLS authenticators can read the verified client certificate.
WithTLSState 将对端 TLS 连接状态写入 context。 传输层(HTTP/gin 或 gRPC)注入该值,供 mTLS 认证器读取已验证的客户端证书。
Types ¶
type Authorizer ¶ added in v0.2.0
type Authorizer interface {
// Enforce checks whether the subject (sub) is permitted to access resource (obj) with action (act).
Enforce(ctx context.Context, sub, obj, act string) (bool, error)
}
Authorizer defines the minimal authorization contract.
type CaptchaStore ¶ added in v0.3.0
type CaptchaStore interface {
// Set stores the captcha value associated with the given id.
// Set 存储与给定 id 关联的验证码值。
Set(id string, value string) error
// Get retrieves the captcha value associated with the given id.
// If clear is true, the captcha value will be deleted after reading.
// Get 获取与给定 id 关联的验证码值。如果 clear 为 true,则读取后清除。
Get(id string, clear bool) string
// Verify checks whether the answer matches the stored captcha value.
// If clear is true, the captcha value will be deleted upon verification.
// Verify 校验答案是否与存储的验证码相符。如果 clear 为 true,校验后清除。
Verify(id, answer string, clear bool) bool
}
CaptchaStore defines the unified interface for captcha storage, compatible with base64Captcha.Store.
CaptchaStore 定义统一的验证码存储接口,与 base64Captcha.Store 规范完全兼容。
type Container ¶
type Container = runtimecontract.Container
Container defines the minimal container surface needed by service auth providers. Reuses the runtime contract's Container for type compatibility.
Container 定义服务鉴权 provider 所需的最小容器接口面。 复用 runtime 契约的 Container,确保类型兼容。
type JWTClaims ¶
type JWTClaims struct {
SubjectID int64
SubjectType string
SubjectName string
Roles []string
Permissions []string // Fine-grained permissions (e.g. "order:create", "user:delete")
ExpiresAt int64
IssuedAt int64
Issuer string
Audience string
}
JWTClaims describes the shared business JWT claims model.
JWTClaims 描述共享的业务 JWT claims 模型。
type JWTService ¶
type JWTService interface {
// Sign signs one set of JWT claims.
//
// Sign 对一组 JWT claims 进行签发。
Sign(claims JWTClaims) (string, error)
// Verify verifies one JWT token and returns claims.
//
// Verify 校验一个 JWT token 并返回 claims。
Verify(token string) (*JWTClaims, error)
// NewClaims builds one standard JWT claims object.
//
// NewClaims 构建一份标准 JWT claims。
NewClaims(subjectID int64, subjectType, subjectName string, roles []string, ttlSeconds int64) JWTClaims
}
JWTService defines the minimal business JWT contract.
JWTService 定义最小业务 JWT 契约。
中文说明: - 这是给业务项目直接使用的最小认证能力。 - 不承载 session 存储,只负责 JWT 签发与校验。 - 它与 service_auth.go 中的“服务间身份认证”是两条独立主线。 - 可被 gin middleware、HTTP handler 和业务 service 复用。
type ServiceAuthConfig ¶
type ServiceAuthConfig struct {
Mode string
ServiceName string
Namespace string
Environment string
MTLSEnabled bool
MTLSCertFile string
MTLSKeyFile string
MTLSCAFile string
MTLSServerName string
TokenSecret string
TokenExpiry int64
TokenIssuer string
TokenAudience string
AllowedServices []string
}
ServiceAuthConfig describes service-auth configuration.
ServiceAuthConfig 描述服务鉴权配置。
type ServiceAuthProvider ¶
type ServiceAuthProvider interface {
ServiceProvider
// CreateAuthenticator creates a service authenticator from config.
//
// CreateAuthenticator 根据配置创建服务认证器。
CreateAuthenticator(cfg *ServiceAuthConfig) (ServiceAuthenticator, error)
}
ServiceAuthProvider defines the provider contract for creating service authenticators.
ServiceAuthProvider 定义创建服务认证器的 provider 契约。
type ServiceAuthenticator ¶
type ServiceAuthenticator interface {
// Authenticate authenticates the current request and returns the resolved service identity.
//
// Authenticate 认证当前请求并返回解析出的服务身份。
Authenticate(ctx context.Context) (*ServiceIdentity, error)
}
ServiceAuthenticator defines the service-identity authentication contract.
ServiceAuthenticator 定义服务身份认证契约。
type ServiceIdentity ¶
type ServiceIdentity struct {
ServiceID string
ServiceName string
Namespace string
Environment string
Metadata map[string]string
}
ServiceIdentity describes one authenticated service identity.
ServiceIdentity 描述一个已认证的服务身份。
func FromServiceIdentityContext ¶
func FromServiceIdentityContext(ctx context.Context) (*ServiceIdentity, bool)
FromServiceIdentityContext retrieves service identity from context.
FromServiceIdentityContext 从 context 中读取服务身份。
type ServicePeerCertificateAuthenticator ¶
type ServicePeerCertificateAuthenticator interface {
// AuthenticatePeerCertificate authenticates the peer certificate and returns the resolved service identity.
//
// AuthenticatePeerCertificate 校验对端证书并返回解析出的服务身份。
AuthenticatePeerCertificate(ctx context.Context, cert *x509.Certificate) (*ServiceIdentity, error)
}
ServicePeerCertificateAuthenticator defines peer-certificate authentication for service identity.
ServicePeerCertificateAuthenticator 定义基于对端证书的服务身份认证契约。
type ServiceProvider ¶
type ServiceProvider = runtimecontract.ServiceProvider
ServiceProvider defines the provider registration surface needed by service auth providers. Reuses the runtime contract's ServiceProvider to avoid duplicate, incompatible definitions.
ServiceProvider 定义服务鉴权 provider 所需的 provider 注册接口面。 复用 runtime 契约的 ServiceProvider,避免重复且不兼容的定义。
type ServiceTokenIssuer ¶
type ServiceTokenIssuer interface {
// GenerateToken generates a token for the target service.
//
// GenerateToken 为目标服务生成令牌。
GenerateToken(ctx context.Context, targetService string) (string, error)
}
ServiceTokenIssuer defines the service token issuing contract.
ServiceTokenIssuer 定义服务令牌签发契约。
type ServiceTokenVerifier ¶
type ServiceTokenVerifier interface {
// VerifyToken verifies a token and returns the resolved service identity.
//
// VerifyToken 校验令牌并返回解析出的服务身份。
VerifyToken(ctx context.Context, token string) (*ServiceIdentity, error)
}
ServiceTokenVerifier defines the service token verification contract.
ServiceTokenVerifier 定义服务令牌校验契约。
type TLSCertificateLoader ¶
type TLSCertificateLoader interface {
LoadCertificate(certFile, keyFile string) (*tls.Certificate, error)
LoadCA(caFile string) (*x509.CertPool, error)
}
TLSCertificateLoader defines the certificate-loading contract used by mTLS auth providers.
TLSCertificateLoader 定义 mTLS 鉴权 provider 使用的证书加载契约。