jwt

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package jwt provides Gin HTTP middleware for JWT authentication. The middleware extracts Bearer token from Authorization header, verifies it, and injects claims into request context. Supports SkipPaths option to skip authentication for specific paths. Context keys:

本文件提供 Gin HTTP 中间件,用于 JWT 认证。 中间件从 Authorization header 提取 Bearer token,验证后注入 context。 支持 SkipPaths 选项跳过指定路径的认证。 Context 键:

  • ContextJWTClaimsKey: JWT claims
  • ContextSubjectIDKey: Subject ID
  • ContextSubjectTypeKey: Subject type

Eg:

// 基本用法
router.Use(jwt.AuthMiddleware(jwtSvc, "user"))

// 全局注册 + 白名单跳过
router.Use(jwt.AuthMiddleware(jwtSvc, "",
    jwt.WithSkipPaths("/api/v1/auth/login", "/api/v1/auth/register"),
))

// 从 context 获取 claims
claims, ok := jwt.ClaimsFromRequestContext(ctx)
subjectID, ok := jwt.SubjectIDFromRequestContext(ctx)

Package jwt provides helper functions for JWT service integration. These helpers simplify JWT service creation and configuration retrieval.

本文件提供 JWT 服务集成的辅助函数。 这些辅助函数简化 JWT 服务创建和配置获取。

Package jwt provides JWT service implementation using HS256 algorithm. The implementation is a lightweight JWT service without external dependencies. Note: This implementation only supports HS256 algorithm.

本文件提供 JWT 服务实现,使用 HS256 算法。 此实现是轻量级 JWT 服务,无需外部依赖。 注意:此实现仅支持 HS256 算法。

Package jwt provides JWT authentication service for gorp framework. The provider reads JWT configuration from config service. Configuration via config.yaml:

JWT 认证包,提供基于 JWT 的身份认证能力。 Provider 从配置服务读取 JWT 配置。 通过 config.yaml 配置:

auth:
  jwt:
    secret: "your-secret-key"
    issuer: "your-service-name"
    audience: "your-audience"
  jwt_secret: "fallback-secret"  # legacy config key

Eg:

// 注册 Provider
app.Register(jwt.NewProvider())

// 使用 JWT 服务
jwtSvc := c.MustMake(securitycontract.AuthJWTKey).(securitycontract.JWTService)
token, _ := jwtSvc.Sign(claims)
claims, _ := jwtSvc.Verify(token)

Index

Constants

View Source
const (
	// ContextJWTClaimsKey is the key for JWT claims in Gin context.
	//
	// ContextJWTClaimsKey 是 Gin context 中 JWT claims 的键。
	ContextJWTClaimsKey = "framework.jwt.claims"
	// ContextSubjectIDKey is the key for subject ID in Gin context.
	//
	// ContextSubjectIDKey 是 Gin context 中主体 ID 的键。
	ContextSubjectIDKey = "framework.subject.id"
	// ContextSubjectTypeKey is the key for subject type in Gin context.
	//
	// ContextSubjectTypeKey 是 Gin context 中主体类型的键。
	ContextSubjectTypeKey = "framework.subject.type"
)

Context keys for storing JWT information in Gin context.

Gin context 中存储 JWT 信息的键。

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(jwtSvc securitycontract.JWTService, expectedSubjectType string, opts ...AuthMiddlewareOption) transportcontract.Middleware

AuthMiddleware creates an HTTP middleware for JWT authentication. Core logic: Extract Bearer token, verify with JWT service, inject claims to context. Supports SkipPaths to skip authentication for specific paths (e.g., login, register).

AuthMiddleware 创建用于 JWT 认证的 HTTP 中间件。 核心逻辑:提取 Bearer token,用 JWT 服务验证,将 claims 注入 context。 支持 SkipPaths 跳过指定路径的认证(如登录、注册接口)。

Parameters:

  • jwtSvc: JWT service for token verification
  • expectedSubjectType: optional subject type validation (empty means no check)
  • opts: optional configuration (WithSkipPaths, WithRequiredRoles)

Returns 401 if token is missing or invalid, 403 if subject type or role mismatch.

token 缺失或无效返回 401,主体类型或角色不匹配返回 403。

func ClaimsFromRequestContext

func ClaimsFromRequestContext(ctx context.Context) (*securitycontract.JWTClaims, bool)

ClaimsFromRequestContext extracts JWT claims from request context.

ClaimsFromRequestContext 从请求 context 提取 JWT claims。

func JWTSecretFromConfig

func JWTSecretFromConfig(cfg datacontract.Config) string

JWTSecretFromConfig retrieves JWT secret from config service. Checks both "auth.jwt.secret" and legacy "auth.jwt_secret" keys. Returns empty string if not found.

JWTSecretFromConfig 从配置服务获取 JWT secret。 同时检查 "auth.jwt.secret" 和遗留的 "auth.jwt_secret" 配置键。 未找到时返回空字符串。

func MustMakeJWTService

MustMakeJWTService retrieves JWT service from container, panics on failure. Use this when JWT service is guaranteed to be available.

MustMakeJWTService 从容器获取 JWT 服务,失败时 panic。 当 JWT 服务保证可用时使用此函数。

func SubjectIDFromContext

func SubjectIDFromContext(c *gin.Context) (int64, bool)

SubjectIDFromContext extracts subject ID from Gin context.

SubjectIDFromContext 从 Gin context 提取主体 ID。

func SubjectIDFromRequestContext

func SubjectIDFromRequestContext(ctx context.Context) (int64, bool)

SubjectIDFromRequestContext extracts subject ID from request context.

SubjectIDFromRequestContext 从请求 context 提取主体 ID。

func SubjectTypeFromRequestContext

func SubjectTypeFromRequestContext(ctx context.Context) (string, bool)

SubjectTypeFromRequestContext extracts subject type from request context.

SubjectTypeFromRequestContext 从请求 context 提取主体类型。

Types

type AuthMiddlewareOption

type AuthMiddlewareOption func(*authMiddlewareConfig)

AuthMiddlewareOption 是 JWT 认证中间件的配置选项函数。

AuthMiddlewareOption is the config option function for JWT auth middleware.

func WithRequiredRoles

func WithRequiredRoles(roles ...string) AuthMiddlewareOption

WithRequiredRoles 设置访问所需的角色列表。 JWT claims 中的 Roles 至少包含其中一个角色才能通过。 为空时不做角色校验。

WithRequiredRoles sets the required roles for access. JWT claims must contain at least one of the specified roles. Empty means no role check.

func WithSkipPaths

func WithSkipPaths(paths ...string) AuthMiddlewareOption

WithSkipPaths 设置不需要认证的路径白名单。 匹配规则:精确匹配请求路径(不含 query string)。 适用于全局注册中间件后,跳过 /api/v1/auth/login 等公开接口。

WithSkipPaths sets the path whitelist that skips authentication. Matching rule: exact match on request path (excluding query string). Use when registering middleware globally but need to skip public endpoints.

type JWTService

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

JWTService implements securitycontract.JWTService using HS256 algorithm.

JWTService 使用 HS256 算法实现 securitycontract.JWTService 接口。

func NewJWTService

func NewJWTService(secret, issuer, audience string) *JWTService

NewJWTService creates a new JWT service instance. If secret is empty, a warning is logged because JWT operations will fail.

NewJWTService 创建新的 JWT 服务实例。 如果 secret 为空,会记录警告日志,因为 JWT 操作将会失败。

func (*JWTService) NewClaims

func (s *JWTService) NewClaims(subjectID int64, subjectType, subjectName string, roles []string, ttlSeconds int64) securitycontract.JWTClaims

NewClaims creates a new JWTClaims with default TTL (24 hours if not specified). Parameters: subjectID, subjectType, subjectName, roles, ttlSeconds.

NewClaims 创建新的 JWTClaims,默认 TTL 为 24 小时(未指定时)。 参数:主体 ID、主体类型、主体名称、角色列表、有效期秒数。

func (*JWTService) Sign

func (s *JWTService) Sign(claims securitycontract.JWTClaims) (string, error)

Sign generates a JWT token from the given claims. Core logic: Create header and payload JSON, encode with base64, sign with HMAC-SHA256. Eg:

Sign 根据给定的声明生成 JWT token。 核心逻辑:创建 header 和 payload JSON,base64 编码,用 HMAC-SHA256 签名。 Eg:

claims := jwtSvc.NewClaims(123, "user", "John", []string{"admin"}, 3600)
token, err := jwtSvc.Sign(claims)

func (*JWTService) Verify

func (s *JWTService) Verify(token string) (*securitycontract.JWTClaims, error)

Verify validates a JWT token and returns the claims. Core logic: Split token into parts, verify signature, decode payload, check expiration. Returns error if token is invalid, signature mismatched, or expired.

Verify 验证 JWT token 并返回声明。 核心逻辑:分割 token 为三部分,验证签名,解码 payload,检查过期时间。 token 无效、签名不匹配或过期时返回错误。

type Provider

type Provider struct{}

Provider registers the JWT authentication service contract.

Provider 注册 JWT 认证服务契约。

func NewProvider

func NewProvider() *Provider

NewProvider creates a new JWT provider instance.

NewProvider 创建新的 JWT Provider 实例。

func (*Provider) Boot

Boot is a no-op for JWT provider.

Boot JWT Provider 无启动逻辑。

func (*Provider) DependsOn

func (p *Provider) DependsOn() []string

DependsOn returns the keys this provider depends on. JWT provider depends on Config for JWT configuration.

DependsOn 返回该 provider 依赖的 key。 JWT provider 依赖 Config 获取 JWT 配置。

func (*Provider) IsDefer

func (p *Provider) IsDefer() bool

IsDefer returns true, JWT service can be deferred until first use.

IsDefer 返回 true,JWT 服务可延迟初始化直到首次使用。

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name "auth.jwt".

Name 返回 Provider 名称 "auth.jwt"。

func (*Provider) Provides

func (p *Provider) Provides() []string

Provides returns the JWT service contract key.

Provides 返回 JWT 服务契约键。

func (*Provider) Register

func (p *Provider) Register(c runtimecontract.Container) error

Register binds the JWT service factory to the container. Core logic: Read secret, issuer, audience from config, create JWTService. Note: Uses fallback secret if not configured (should change in production).

Register 将 JWT 服务工厂绑定到容器。 核心逻辑:从配置读取 secret、issuer、audience,创建 JWTService。 注意:未配置时使用默认 secret(生产环境应修改)。

Jump to

Keyboard shortcuts

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