security

package
v0.1.27 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 7 Imported by: 0

README

Mist框架安全模块

Mist框架安全模块提供了全面的Web应用安全功能,包括会话管理、认证、CSRF保护、限流、安全HTTP头、密码处理以及多因素认证等。

主要功能

  • 会话管理:支持Redis后端的会话存储、JWT令牌
  • 身份认证:基于JWT的身份验证系统
  • CSRF保护:防止跨站请求伪造攻击
  • 请求限流:防止API滥用和DoS攻击
  • 安全HTTP头:自动添加安全相关的HTTP头
  • 密码处理:安全的密码哈希和验证
  • 安全配置:支持不同安全级别(基础、中级、严格)的预设配置
  • 多因素认证(MFA):支持基于TOTP的两步验证
  • IP黑名单:防止暴力破解攻击

快速开始

设置安全级别
package main

import (
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security"
)

func main() {
	// 设置安全级别(基础、中级、严格)
	security.SetSecurityLevel(security.LevelIntermediate)
	
	// 创建应用实例
	app := mist.InitHTTPServer()
	
	// 路由和其他配置...
	
	app.Run(":8080")
}
使用CSRF保护
package main

import (
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/csrf"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 添加CSRF中间件
	app.Use(csrf.New())
	
	// 自定义CSRF保护配置
	app.Use(csrf.New(
		csrf.WithTokenLength(64),
		csrf.WithCookieName("my_csrf_token"),
		csrf.WithHeaderName("X-My-CSRF-Token"),
	))
	
	app.Run(":8080")
}
使用限流功能
package main

import (
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/ratelimit"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 创建内存限流器(每秒10个请求,突发20个请求)
	limiter := ratelimit.NewMemoryLimiter(10, 20)
	
	// 添加限流中间件
	app.Use(ratelimit.New(limiter,
		ratelimit.WithRate(10),
		ratelimit.WithBurst(20),
		ratelimit.WithKeyExtractor(ratelimit.IPKeyExtractor),
	))
	
	// 为特定API路由添加更严格的限流
	apiGroup := app.Group("/api")
	apiLimiter := ratelimit.NewMemoryLimiter(5, 10)
	apiGroup.Use(ratelimit.New(apiLimiter))
	
	app.Run(":8080")
}
使用安全HTTP头
package main

import (
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/headers"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 添加安全头部中间件(使用默认配置)
	app.Use(headers.New())
	
	// 自定义安全头部配置
	app.Use(headers.New(
		headers.WithXSSProtection(true),
		headers.WithHSTS(true, 63072000, true, true),
		headers.WithContentSecurityPolicy(headers.CSPStrict()),
	))
	
	app.Run(":8080")
}
使用密码处理
package main

import (
	"fmt"
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/password"
)

func registerHandler(ctx *mist.Context) {
	username := ctx.PostForm("username")
	plainPassword := ctx.PostForm("password")
	
	// 检查密码强度
	strength := password.CheckPasswordStrength(plainPassword)
	if strength < password.Medium {
		ctx.AbortWithStatus(400) // 密码强度不足
		return
	}
	
	// 哈希密码
	hashedPassword, err := password.HashPassword(plainPassword)
	if err != nil {
		ctx.AbortWithStatus(500) // 密码处理错误
		return
	}
	
	// 存储用户信息...
	fmt.Println("哈希后的密码:", hashedPassword)
}

func loginHandler(ctx *mist.Context) {
	username := ctx.PostForm("username")
	plainPassword := ctx.PostForm("password")
	
	// 从数据库获取哈希后的密码...
	storedHash := getPasswordFromDatabase(username)
	
	// 验证密码
	err := password.CheckPassword(plainPassword, storedHash)
	if err != nil {
		ctx.AbortWithStatus(401) // 用户名或密码错误
		return
	}
	
	// 登录成功,创建会话...
}
会话管理
package main

import (
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security"
	"github.com/dormoron/mist/security/redisess"
	"github.com/redis/go-redis/v9"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 配置Redis客户端
	redisClient := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	
	// 创建基于Redis的会话提供者
	provider := redisess.InitSessionProvider(redisClient, "your-jwt-secret-key")
	
	// 设置全局会话提供者
	security.SetDefaultProvider(provider)
	
	// 添加登录检查中间件
	app.Use(security.CheckLoginMiddleware("/admin", "/profile", "/api"))
	
	app.Run(":8080")
}
使用多因素认证(MFA)
package main

import (
	"time"
	
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/mfa"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 创建内存存储的MFA验证状态管理器
	store := mfa.NewMemoryStore()
	
	// 创建MFA中间件
	mfaMiddleware := mfa.NewMiddleware(
		mfa.WithStore(store),
		mfa.WithValidationDuration(24 * time.Hour),
		mfa.WithRedirectURL("/mfa/validate"),
	)
	
	// 应用MFA中间件到需要保护的路由
	adminGroup := app.Group("/admin")
	adminGroup.Use(mfaMiddleware)
	
	// MFA验证处理
	app.POST("/mfa/validate", func(ctx *mist.Context) {
		userID := getUserID(ctx) // 从会话或上下文中获取用户ID
		code := ctx.PostForm("code")
		
		// 从数据库获取用户的TOTP密钥
		secretKey := getUserTOTPSecret(userID)
		
		// 创建TOTP实例
		totp := mfa.NewTOTPWithSecret(secretKey)
		
		// 验证TOTP代码
		err := mfa.Validate(ctx, userID, code, totp, store, 24*time.Hour)
		if err != nil {
			ctx.AbortWithStatus(400) // 验证码无效
			return
		}
		
		// 验证成功,重定向到原始目标页面
		ctx.Redirect(302, "/admin")
	})
	
	// 生成TOTP二维码链接
	app.GET("/mfa/setup", func(ctx *mist.Context) {
		userID := getUserID(ctx)
		
		// 创建新的TOTP实例
		totp, err := mfa.NewTOTP()
		if err != nil {
			ctx.AbortWithStatus(500)
			return
		}
		
		// 存储用户的TOTP密钥到数据库
		saveUserTOTPSecret(userID, totp.Secret)
		
		// 生成配置URI(用于QR码)
		provisioningURI := totp.ProvisioningURI(userID)
		
		// 返回URI(前端可以用它生成QR码)
		ctx.JSON(200, map[string]string{
			"uri": provisioningURI,
		})
	})
	
	app.Run(":8080")
}
使用IP黑名单防止暴力破解
package main

import (
	"time"
	
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security/blocklist"
)

func main() {
	app := mist.InitHTTPServer()
	
	// 创建IP黑名单管理器
	blocklistManager := blocklist.NewManager(
		blocklist.WithMaxFailedAttempts(5),        // 5次失败尝试后封禁
		blocklist.WithBlockDuration(30*time.Minute), // 封禁30分钟
		blocklist.WithWhitelistIPs([]string{"127.0.0.1"}), // 白名单IP
	)
	
	// 添加IP黑名单中间件
	app.Use(blocklistManager.Middleware())
	
	// 登录处理
	app.POST("/login", func(ctx *mist.Context) {
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")
		
		// 获取客户端IP
		ip := ctx.ClientIP()
		
		// 验证用户名和密码
		if validateCredentials(username, password) {
			// 登录成功,记录成功并重置失败计数
			blocklistManager.RecordSuccess(ip)
			// 处理登录成功...
		} else {
			// 登录失败,记录失败
			blocked := blocklistManager.RecordFailure(ip)
			if blocked {
				// IP已被封禁,返回特定错误
				ctx.AbortWithStatus(403) // 已被封禁
			} else {
				// 未被封禁,但登录失败
				ctx.AbortWithStatus(401) // 用户名或密码错误
			}
		}
	})
	
	// 手动封禁IP
	app.POST("/admin/block-ip", func(ctx *mist.Context) {
		ip := ctx.PostForm("ip")
		duration := 24 * time.Hour // 封禁24小时
		
		blocklistManager.BlockIP(ip, duration)
		ctx.String(200, "IP已被封禁")
	})
	
	// 手动解除IP封禁
	app.POST("/admin/unblock-ip", func(ctx *mist.Context) {
		ip := ctx.PostForm("ip")
		
		blocklistManager.UnblockIP(ip)
		ctx.String(200, "IP封禁已解除")
	})
	
	app.Run(":8080")
}

安全配置

Mist框架提供了三种预设的安全级别:

  1. LevelBasic:基础安全级别,适合开发环境或不太敏感的应用
  2. LevelIntermediate:中级安全级别,适合一般Web应用(默认)
  3. LevelStrict:严格安全级别,适合处理敏感数据的应用

可以通过security.SetSecurityLevel()设置全局安全级别,或创建自定义配置:

// 自定义安全配置
customConfig := security.DefaultSecurityConfig(security.LevelIntermediate)
customConfig.Password.MinLength = 12
customConfig.Session.AccessTokenExpiry = 30 * time.Minute
customConfig.CSRF.TokenLength = 64

// 应用自定义配置
security.SetSecurityConfig(customConfig)

最佳实践

  1. 为生产环境使用至少LevelIntermediate安全级别
  2. 确保所有敏感操作受CSRF保护
  3. 为关键API端点设置适当的速率限制
  4. 对所有用户密码使用password包提供的哈希功能
  5. 启用安全HTTP头以增强前端安全性
  6. 为敏感账户启用多因素认证
  7. 使用IP黑名单防止暴力破解攻击
  8. 定期轮换JWT密钥和会话密钥

完整示例

package main

import (
	"time"
	
	"github.com/dormoron/mist"
	"github.com/dormoron/mist/security"
	"github.com/dormoron/mist/security/csrf"
	"github.com/dormoron/mist/security/blocklist/middleware"
	"github.com/dormoron/mist/security/headers"
	"github.com/dormoron/mist/security/ratelimit"
	"github.com/dormoron/mist/security/redisess"
	"github.com/dormoron/mist/security/blocklist"
	"github.com/dormoron/mist/security/mfa"
	"github.com/redis/go-redis/v9"
)

func main() {
	// 设置安全级别
	security.SetSecurityLevel(security.LevelStrict)
	
	// 创建应用实例
	app := mist.InitHTTPServer()
	
	// 配置Redis客户端
	redisClient := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	
	// 会话管理
	provider := redisess.InitSessionProvider(redisClient, "your-secret-key")
	security.SetDefaultProvider(provider)
	
	// IP黑名单
	blocklistManager := blocklist.NewManager(
		blocklist.WithMaxFailedAttempts(5),
		blocklist.WithBlockDuration(30*time.Minute),
	)
	
	// MFA验证
	mfaStore := mfa.NewMemoryStore()
	mfaMiddleware := mfa.NewMiddleware(
		mfa.WithStore(mfaStore),
		mfa.WithValidationDuration(24*time.Hour),
	)
	
	// 添加安全中间件
	
	// 1. IP黑名单
	app.Use(middleware.New(blocklistManager))
	
	// 2. 安全HTTP头
	app.Use(headers.New(
		headers.WithContentSecurityPolicy(headers.CSPStrict()),
	))
	
	// 3. CSRF保护
	app.Use(csrf.New())
	
	// 4. 全局限流(每秒100请求)
	globalLimiter := ratelimit.NewMemoryLimiter(100, 200)
	app.Use(ratelimit.New(globalLimiter))
	
	// 5. 登录检查
	app.Use(security.CheckLoginMiddleware("/admin", "/profile", "/api"))
	
	// API路由组
	apiGroup := app.Group("/api")
	
	// API特定限流(每秒10请求)
	apiLimiter := ratelimit.NewMemoryLimiter(10, 20) 
	apiGroup.Use(ratelimit.New(apiLimiter))
	
	// 管理员路由组(需要MFA验证)
	adminGroup := app.Group("/admin")
	adminGroup.Use(mfaMiddleware)
	
	// 设置路由
	app.GET("/", func(ctx *mist.Context) {
		ctx.String(200, "Mist Framework with Security")
	})
	
	// 登录处理
	app.POST("/login", handleLogin(blocklistManager))
	
	// MFA相关路由
	app.POST("/mfa/validate", handleMFAValidation(mfaStore))
	app.GET("/mfa/setup", handleMFASetup())
	
	// 启动服务器
	app.Run(":8080")
}

// 登录处理函数
func handleLogin(bm *blocklist.Manager) mist.HandleFunc {
	return func(ctx *mist.Context) {
		// 登录逻辑...
	}
}

// MFA验证处理函数
func handleMFAValidation(store mfa.ValidationStore) mist.HandleFunc {
	return func(ctx *mist.Context) {
		// MFA验证逻辑...
	}
}

// MFA设置处理函数
func handleMFASetup() mist.HandleFunc {
	return func(ctx *mist.Context) {
		// MFA设置逻辑...
	}
}

4. IP 黑名单(Blocklist)

Mist框架提供了IP黑名单功能,用于限制恶意IP访问系统,防止暴力破解等攻击。

4.1 快速开始
import (
    "github.com/dormoron/mist"
    "github.com/dormoron/mist/security/blocklist"
    "github.com/dormoron/mist/security/blocklist/middleware"
    "time"
)

// 创建IP黑名单管理器
blocklistManager := blocklist.NewManager(
    blocklist.WithMaxFailedAttempts(5),          // 最大失败尝试次数
    blocklist.WithBlockDuration(15*time.Minute), // 封禁时长
    blocklist.WithWhitelistIPs([]string{"127.0.0.1"}), // 白名单IP
)

// 在Mist框架中使用(推荐方式)
app := mist.New()
// 使用默认配置(返回403 Forbidden状态码)
app.Use(middleware.New(blocklistManager))

// 使用自定义处理函数
app.Use(middleware.New(
    blocklistManager,
    middleware.WithOnBlocked(func(ctx *mist.Context) {
        ctx.AbortWithStatus(http.StatusForbidden)
        // 或者返回JSON响应
        // ctx.RespondWithJSON(http.StatusForbidden, map[string]string{
        //     "error": "您的IP已被暂时封禁,请稍后再试",
        // })
    }),
))

// 在标准HTTP服务中使用
http.Handle("/api", blocklistManager.Middleware()(yourHandler))
4.2 配置选项
// 创建具有自定义配置的IP黑名单管理器
manager := blocklist.NewManager(
    // 设置最大失败尝试次数,超过后IP将被封禁
    blocklist.WithMaxFailedAttempts(3),
    
    // 设置封禁时长
    blocklist.WithBlockDuration(30*time.Minute),
    
    // 设置清理过期记录的间隔
    blocklist.WithClearInterval(10*time.Minute),
    
    // 设置IP白名单,这些IP不会被封禁
    blocklist.WithWhitelistIPs([]string{"127.0.0.1", "192.168.1.1"}),
    
    // 设置封禁时的响应处理函数(标准HTTP中间件)
    blocklist.WithOnBlocked(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusForbidden)
        w.Write([]byte("您的IP已被暂时封禁,请稍后再试"))
    }),
)

// 在Mist框架中使用自定义封禁处理函数
app.Use(manager.MistMiddleware(
    blocklist.WithMistOnBlocked(func(ctx *mist.Context) {
        // 记录IP被封禁事件
        log.Printf("IP %s 因多次失败尝试被封禁", ctx.ClientIP())
        
        // 返回自定义错误响应
        ctx.RespondWithJSON(http.StatusForbidden, map[string]string{
            "error": "您的IP因多次失败的尝试已被封禁",
            "retry_after": "30分钟后再试",
        })
    }),
))
4.3 记录登录失败和成功

在登录过程中,您可以使用以下方法记录成功和失败的登录尝试:

// 处理登录请求
func handleLogin(w http.ResponseWriter, r *http.Request) {
    ip := getClientIP(r) // 获取客户端IP
    
    // 检查IP是否已被封禁
    if blocklistManager.IsBlocked(ip) {
        http.Error(w, "您的IP已被封禁,请稍后再试", http.StatusForbidden)
        return
    }
    
    // 执行验证...
    if loginSuccessful {
        // 记录成功的登录,重置失败计数
        blocklistManager.RecordSuccess(ip)
        // 继续正常登录流程...
    } else {
        // 记录失败的登录,增加失败计数
        isBlocked := blocklistManager.RecordFailure(ip)
        if isBlocked {
            http.Error(w, "您的IP因多次失败的尝试已被封禁", http.StatusForbidden)
        } else {
            http.Error(w, "用户名或密码错误", http.StatusUnauthorized)
        }
    }
}
4.4 手动管理IP封禁

您可以手动封禁和解除封禁IP:

// 手动封禁IP,指定封禁时长
blocklistManager.BlockIP("192.168.1.100", 2*time.Hour)

// 解除IP封禁
blocklistManager.UnblockIP("192.168.1.100")

// 检查IP是否被封禁
isBlocked := blocklistManager.IsBlocked("192.168.1.100")

Documentation

Index

Constants

View Source
const CtxSessionKey = "_session"

CtxSessionKey is a constant string used as a key for storing session data in the context.

Variables

This section is empty.

Functions

func AccountLockoutMiddleware added in v0.1.26

func AccountLockoutMiddleware() mist.HandleFunc

AccountLockoutMiddleware 创建账户锁定中间件

func CheckLoginMiddleware

func CheckLoginMiddleware(paths ...string) mist.Middleware

CheckLoginMiddleware creates a middleware that checks if the user is logged in for specified paths. Parameters: - paths: A variadic list of URL paths to be checked (string). Returns: - mist.Middleware: The constructed middleware.

func CleanupSecurity added in v0.1.26

func CleanupSecurity()

CleanupSecurity 清理安全相关资源

func ClearToken added in v0.1.12

func ClearToken(ctx *mist.Context) error

ClearToken is a function that serves as a wrapper to invoke the ClearToken method of the defaultProvider. It clears the access and refresh tokens for a session by leveraging the default session provider.

Parameters:

  • ctx: The mist.Context object representing the current HTTP request and response.

Returns:

  • An error object if the underlying ClearToken method in defaultProvider fails, otherwise it returns nil.

func Middleware added in v0.1.26

func Middleware() mist.HandleFunc

Middleware 创建全局安全中间件

func RecordFailedLoginAttempt added in v0.1.26

func RecordFailedLoginAttempt(ctx *mist.Context) bool

RecordFailedLoginAttempt 记录失败的登录尝试

func RenewAccessToken

func RenewAccessToken(ctx *mist.Context) error

RenewAccessToken renews the access token for the session associated with the given context. Parameters: - ctx: The request context (*mist.Context). Returns: - error: An error if the token renewal fails.

func ResetLockout added in v0.1.26

func ResetLockout(ctx *mist.Context)

ResetLockout 重置账户锁定

func SessionWithSecurityMiddleware added in v0.1.26

func SessionWithSecurityMiddleware(manager *session.Manager) mist.HandleFunc

SessionWithSecurityMiddleware 创建增强的安全会话中间件

func SetDefaultProvider

func SetDefaultProvider(sp Provider)

SetDefaultProvider sets the default session provider. Parameters: - sp: The session provider to be set as the default (Provider).

func SetSecurityConfig added in v0.1.20

func SetSecurityConfig(config SecurityConfig)

SetSecurityConfig 设置全局安全配置

func SetSecurityLevel added in v0.1.20

func SetSecurityLevel(level SecurityLevel)

SetSecurityLevel 设置全局安全级别

func UpdateClaims

func UpdateClaims(ctx *mist.Context, claims Claims) error

UpdateClaims updates the claims for the session associated with the given context. Parameters: - ctx: The request context (*mist.Context). - claims: The claims to be updated (Claims). Returns: - error: An error if the claims update fails.

Types

type AccountLockoutConfig added in v0.1.26

type AccountLockoutConfig struct {
	// Enabled 是否启用账户锁定
	Enabled bool

	// MaxAttempts 允许的最大失败尝试次数
	MaxAttempts int

	// LockoutDuration 锁定持续时间
	LockoutDuration time.Duration

	// ResetDuration 失败尝试记录重置时间
	ResetDuration time.Duration

	// IncludeIPInKey 是否在锁定键中包含IP地址
	IncludeIPInKey bool

	// CleanupInterval 清理过期锁定记录的间隔
	CleanupInterval time.Duration
}

AccountLockoutConfig 账户锁定配置

type AuthConfig added in v0.1.20

type AuthConfig struct {
	// JWTSecret JWT密钥
	JWTSecret string

	// EnableRefreshToken 是否启用刷新令牌
	EnableRefreshToken bool

	// MaxLoginAttempts 最大登录尝试次数
	MaxLoginAttempts int

	// LockoutDuration 锁定时长
	LockoutDuration time.Duration

	// AccountLockout 账户锁定策略
	AccountLockout AccountLockoutConfig
}

AuthConfig 身份验证配置

type Builder

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

Builder is a structure that helps in building a session configuration step by step. It contains the context, user ID, JWT data, session data, and a session provider.

func InitSessionBuilder added in v0.1.11

func InitSessionBuilder(ctx *mist.Context, uid int64) *Builder

InitSessionBuilder initializes and returns a new instance of Builder with the given context and user ID. The default session provider is set during initialization. Parameters: - ctx: The request context (*mist.Context). - uid: The user ID for the session (int64). Returns: - *Builder: A pointer to a newly created Builder instance.

func (*Builder) Build

func (b *Builder) Build() (Session, error)

Build constructs the session using the provided or default session provider, context, user ID, JWT data, and session data. Returns: - Session: The newly created session. - error: An error if the session creation fails.

func (*Builder) SetJwtData

func (b *Builder) SetJwtData(data map[string]any) *Builder

SetJwtData sets the JWT data for the Builder. Parameters: - data: The JWT-related data (map[string]any). Returns: - *Builder: The Builder instance with the updated JWT data.

func (*Builder) SetProvider

func (b *Builder) SetProvider(p Provider) *Builder

SetProvider sets a custom session provider for the Builder. Parameters: - p: The custom session provider (Provider). Returns: - *Builder: The Builder instance with the updated provider.

func (*Builder) SetSessData

func (b *Builder) SetSessData(data map[string]any) *Builder

SetSessData sets the session data for the Builder. Parameters: - data: The additional session data (map[string]any). Returns: - *Builder: The Builder instance with the updated session data.

type CSRFConfig added in v0.1.20

type CSRFConfig struct {
	// Enabled 是否启用CSRF保护
	Enabled bool

	// TokenLength CSRF令牌长度
	TokenLength int

	// CookieName CSRF Cookie名称
	CookieName string

	// HeaderName CSRF HTTP头名称
	HeaderName string

	// FormField CSRF表单字段名称
	FormField string

	// IgnoreMethods 忽略的HTTP方法
	IgnoreMethods []string
}

CSRFConfig CSRF配置

type Claims

type Claims struct {
	UserID    int64          // User ID
	SessionID string         // Session ID
	Data      map[string]any // Additional data related to the claims
}

Claims structure holds the data associated with the session's JWT claims.

func (Claims) Get

func (c Claims) Get(key string) mist.AnyValue

Get retrieves the value associated with the key from the claims.

type HeadersConfig added in v0.1.20

type HeadersConfig struct {
	// EnableXSSProtection 是否启用XSS防护
	EnableXSSProtection bool

	// EnableContentTypeNosniff 是否启用内容类型嗅探保护
	EnableContentTypeNosniff bool

	// EnableXFrameOptions 是否启用X-Frame-Options
	EnableXFrameOptions bool

	// XFrameOptionsValue X-Frame-Options的值
	XFrameOptionsValue string

	// EnableHSTS 是否启用HSTS
	EnableHSTS bool

	// HSTSMaxAge HSTS最大存活时间
	HSTSMaxAge time.Duration

	// HSTSIncludeSubdomains 是否包含子域名
	HSTSIncludeSubdomains bool

	// HSTSPreload 是否启用预加载
	HSTSPreload bool

	// ContentSecurityPolicy 内容安全策略
	ContentSecurityPolicy string

	// EnablePermissionsPolicy 是否启用权限策略
	EnablePermissionsPolicy bool

	// PermissionsPolicy 权限策略内容
	PermissionsPolicy string

	// EnableCrossOriginPolicies 是否启用跨域策略
	EnableCrossOriginPolicies bool

	// CrossOriginEmbedderPolicy 跨域嵌入者策略
	CrossOriginEmbedderPolicy string

	// CrossOriginOpenerPolicy 跨域打开者策略
	CrossOriginOpenerPolicy string

	// CrossOriginResourcePolicy 跨域资源策略
	CrossOriginResourcePolicy string

	// EnableCacheControl 是否启用缓存控制
	EnableCacheControl bool

	// CacheControl 缓存控制内容
	CacheControl string

	// EnableReferrerPolicy 是否启用引用策略
	EnableReferrerPolicy bool

	// ReferrerPolicy 引用策略内容
	ReferrerPolicy string
}

HeadersConfig 安全HTTP头配置

type MiddlewareBuilder

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

MiddlewareBuilder 是用于构建登录检查中间件的构建器

func InitMiddlewareBuilder added in v0.1.11

func InitMiddlewareBuilder(provider Provider, paths ...string) *MiddlewareBuilder

InitMiddlewareBuilder 初始化一个新的中间件构建器 Parameters: - provider: 会话提供者接口 - paths: 需要检查登录状态的路径 Returns: - *MiddlewareBuilder: 初始化后的中间件构建器

func (*MiddlewareBuilder) Build

func (m *MiddlewareBuilder) Build() mist.Middleware

Build 构建中间件 Returns: - mist.Middleware: 构建的中间件函数

type PasswordConfig added in v0.1.20

type PasswordConfig struct {
	// MinLength 最小长度
	MinLength int

	// RequireUppercase 是否要求大写字母
	RequireUppercase bool

	// RequireLowercase 是否要求小写字母
	RequireLowercase bool

	// RequireDigits 是否要求数字
	RequireDigits bool

	// RequireSpecialChars 是否要求特殊字符
	RequireSpecialChars bool

	// MaxAge 密码最长使用时间
	MaxAge time.Duration

	// PreventReuseCount 禁止重复使用最近密码的数量
	PreventReuseCount int
}

PasswordConfig 密码配置

type Provider

type Provider interface {
	// InitSession initializes a new session with the specified user ID, JWT data, and session data.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
	// - uid: user ID for which the session is being created ('int64')
	// - jwtData: JWT token data (usually claims) to store with the session ('map[string]any')
	// - sessData: additional session-specific data to associate with the session ('map[string]any')
	// Returns:
	// - Session: the initialized session
	// - error: error, if any occurred while initializing the session
	InitSession(ctx *mist.Context, uid int64, jwtData map[string]any, sessData map[string]any) (Session, error)

	// Get retrieves the current session associated with the context.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
	// Returns:
	// - Session: the current session
	// - error: error, if any occurred while retrieving the session
	Get(ctx *mist.Context) (Session, error)

	// UpdateClaims updates the claims associated with the current session.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
	// - claims: a new set of claims to associate with the session ('Claims')
	// Returns:
	// - error: error, if any occurred while updating the claims
	UpdateClaims(ctx *mist.Context, claims Claims) error

	// RenewAccessToken renews the access token associated with the session.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
	// Returns:
	// - error: error, if any occurred while renewing the access token
	RenewAccessToken(ctx *mist.Context) error

	// The ClearToken function is designed to remove or invalidate a security or session token associated with the given context.
	//
	// Parameters:
	// ctx: A pointer to a mist.Context object, which holds contextual information for the function to operate within.
	//      The mist.Context might include various details like user information, request scope, or environmental settings.
	//
	// Return:
	// error: This function returns an error type. If the token clearing process fails for any reason (e.g., token doesn't exist,
	//        network issues, permission issues), the function will return a non-nil error indicating what went wrong.
	//        If the token clearing process is successful, it returns nil.
	ClearToken(ctx *mist.Context) error
}

Provider interface defines methods for session lifecycle management and JWT claim updates.

func DefaultProvider

func DefaultProvider() Provider

DefaultProvider returns the current default session provider. Returns: - Provider: The current default session provider.

type RateLimitConfig added in v0.1.20

type RateLimitConfig struct {
	// Enabled 是否启用限流
	Enabled bool

	// Rate 每秒请求限制
	Rate float64

	// Burst 突发请求限制
	Burst int

	// EnableIPRateLimit 是否启用IP限流
	EnableIPRateLimit bool

	// UseRedisBackend 是否使用Redis后端
	UseRedisBackend bool
}

RateLimitConfig 限流配置

type SecurityConfig added in v0.1.20

type SecurityConfig struct {
	// Level 安全级别
	Level SecurityLevel

	// Session 会话配置
	Session SessionConfig

	// CSRF 防跨站请求伪造配置
	CSRF CSRFConfig

	// RateLimit 请求限流配置
	RateLimit RateLimitConfig

	// Headers HTTP安全头配置
	Headers HeadersConfig

	// Auth 身份验证配置
	Auth AuthConfig

	// Password 密码策略配置
	Password PasswordConfig
}

SecurityConfig 是安全模块的主配置结构

func DefaultSecurityConfig added in v0.1.20

func DefaultSecurityConfig(level SecurityLevel) SecurityConfig

DefaultSecurityConfig 返回基于指定安全级别的默认配置

func GetSecurityConfig added in v0.1.20

func GetSecurityConfig() SecurityConfig

GetSecurityConfig 获取当前全局安全配置

type SecurityLevel added in v0.1.20

type SecurityLevel int

SecurityLevel 表示应用程序的安全级别

const (
	// LevelBasic 基本安全级别,适用于开发或不太敏感的应用
	LevelBasic SecurityLevel = iota
	// LevelIntermediate 中级安全级别,适用于一般Web应用
	LevelIntermediate
	// LevelStrict 严格安全级别,适用于处理敏感数据的应用
	LevelStrict
	// LevelCustom 自定义安全级别,使用用户指定的设置
	LevelCustom
)

func GetSecurityLevel added in v0.1.20

func GetSecurityLevel() SecurityLevel

GetSecurityLevel 获取当前安全级别

type Session

type Session interface {
	// Set assigns a value to a session key. The context is typically used for request-scoped values.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
	// - key: the key under which the value is stored ('string')
	// - val: the value to store, which can be of any type ('any')
	// Returns:
	// - error: error, if any occurred while setting the value
	Set(ctx context.Context, key string, val any) error

	// Get retrieves the value associated with the key from the session.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
	// - key: the key for the value to be retrieved ('string')
	// Returns:
	// - mist.AnyValue: a wrapper containing the retrieved value or an error if the key wasn't found
	Get(ctx context.Context, key string) mist.AnyValue

	// Del deletes the key-value pair associated with the key from the session.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
	// - key: the key for the value to be deleted ('string')
	// Returns:
	// - error: error, if any occurred while deleting the value
	Del(ctx context.Context, key string) error

	// Destroy invalidates the session entirely, clearing all data within the session.
	// Parameters:
	// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
	// Returns:
	// - error: error, if any occurred while destroying the session
	Destroy(ctx context.Context) error

	// Claims retrieves the claims associated with the session. Claims usually contain user-related data, often in a JWT context.
	// Returns:
	// - Claims: a set of claims related to the session
	Claims() Claims
}

Session interface defines multiple methods for session management.

func Get

func Get(ctx *mist.Context) (Session, error)

Get retrieves the session associated with the given context using the default provider. Parameters: - ctx: The request context (*mist.Context). Returns: - Session: The session associated with the context. - error: An error if the session retrieval fails.

func InitSession added in v0.1.11

func InitSession(ctx *mist.Context, uid int64, jwtData map[string]any, sessData map[string]any) (Session, error)

InitSession initializes a new session using the default provider. Parameters: - ctx: The request context (*mist.Context). - uid: User ID for the session (int64). - jwtData: JWT-related data to be included in the session (map[string]any). - sessData: Additional session data (map[string]any). Returns: - Session: The newly created session. - error: An error if the session creation fails.

type SessionConfig added in v0.1.20

type SessionConfig struct {
	// Enabled 是否启用会话管理
	Enabled bool

	// Domain Cookie域名
	Domain string

	// Path Cookie路径
	Path string

	// MaxAge 会话最大存活时间
	MaxAge time.Duration

	// Secure 是否仅通过HTTPS发送Cookie
	Secure bool

	// HttpOnly 是否禁止JavaScript访问Cookie
	HttpOnly bool

	// SameSite Cookie的SameSite属性
	SameSite http.SameSite

	// AccessTokenExpiry 访问令牌过期时间
	AccessTokenExpiry time.Duration

	// RefreshTokenExpiry 刷新令牌过期时间
	RefreshTokenExpiry time.Duration

	// TokenHeader 令牌的HTTP头
	TokenHeader string

	// AccessTokenHeader 访问令牌的HTTP头
	AccessTokenHeader string

	// RefreshTokenHeader 刷新令牌的HTTP头
	RefreshTokenHeader string

	// IdleTimeout 会话闲置超时时间
	IdleTimeout time.Duration

	// AbsoluteTimeout 会话绝对过期时间(无论活动与否)
	AbsoluteTimeout time.Duration

	// EnableFingerprinting 启用会话指纹绑定
	EnableFingerprinting bool

	// RotateTokenOnValidation 每次认证成功后轮换会话令牌
	RotateTokenOnValidation bool

	// RequireReauthForSensitive 敏感操作需要重新验证
	RequireReauthForSensitive bool

	// ReauthTimeout 重新验证超时时间
	ReauthTimeout time.Duration
}

SessionConfig 会话配置

Directories

Path Synopsis
kit
example command
csp
id
example command
example command

Jump to

Keyboard shortcuts

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