Documentation
¶
Overview ¶
Package security 提供安全功能支持,用于 enhance 框架。
Package security 提供安全功能支持,用于 enhance 框架。
该模块提供认证、授权、Web 安全过滤器、速率限制等安全机制,保护应用安全。 参考 Spring Security 的设计理念。
架构设计 ¶
- SecurityContext: 安全上下文接口,管理认证信息
- Authentication: 认证信息接口(别名 → authentication.Authentication)
- AuthenticationManager: 认证管理器接口(别名 → authentication.AuthenticationManager)
- AccessDecisionManager: 访问决策管理器接口(别名 → authorization.AccessDecisionManager)
- UserDetailsService: 用户详情服务接口
- UserDetails: 用户详情接口
- PasswordEncoder: 密码编码器接口
- SecurityFilter: 安全过滤器接口(别名 → filter.Filter)
- SecurityFilterChain: 安全过滤器链接口(别名 → filter.SecurityFilterChain)
- AccessDeniedHandler: 访问拒绝处理器接口
- AuthenticationEntryPoint: 认证入口点接口
- SecurityMetadataSource: 安全元数据源接口
- SecurityRequest: 安全请求接口
- SecurityResponse: 安全响应接口
- GrantedAuthority: 授予权限接口
- HttpSecurity: HTTP 安全配置接口
- AuthorizeRequests: 授权请求配置接口
- ExpressionInterceptUrlRegistry: URL 拦截注册接口
- SecurityConfig: 安全配置接口
- LogoutSuccessHandler: 登出成功处理器接口
- RateLimiter: 速率限制器接口
- CsrfTokenManager: CSRF 令牌管理器接口
核心功能 ¶
- 认证: 支持用户名/密码、JWT、OAuth2 等认证方式
- 授权: 支持基于角色和权限的授权检查
- 安全过滤器: 支持请求拦截和安全检查
- 速率限制: 防止恶意请求和暴力破解
- CSRF 防护: 防止跨站请求伪造攻击
使用方式 ¶
配置安全策略:
httpSec := security.NewHttpSecurity()
httpSec.FormLogin("/login").
Logout("/logout").
Csrf().
AuthorizeRequests(func(authz security.AuthorizeRequests) {
authz.AntMatchers("/api/**").HasRole("ROLE_API")
authz.AnyRequest().Authenticated()
})
认证用户:
auth := security.Authenticate(username, password)
if auth != nil {
// 认证成功
}
检查权限:
if security.HasPermission("user:read") {
// 有权限访问
}
安全过滤器链 ¶
请求经过的过滤器链:
- AuthenticationFilter: 认证过滤器
- AuthorizationFilter: 授权过滤器
- RateLimitFilter: 速率限制过滤器
- CSRFTokenFilter: CSRF 防护过滤器
Package security 提供安全功能支持,用于 enhance 框架。
Package security 提供安全功能支持,用于 enhance 框架。
Package security 提供安全功能支持,用于 enhance 框架。 设计灵感来源于 Spring Security,采用接口设计模式,支持灵活的安全配置。
核心功能: - 认证(Authentication):验证用户身份 - 授权(Authorization):控制资源访问权限 - 安全上下文(SecurityContext):线程安全的认证信息存储 - 过滤器链(FilterChain):可配置的安全过滤器执行链
Index ¶
- Constants
- Variables
- func ContextWithAuthentication(ctx context.Context, auth Authentication) context.Context
- type AccessDecisionManager
- type AccessDecisionVoter
- type AccessDeniedHandler
- type AffirmativeBased
- func (m *AffirmativeBased) AddVoter(voter AccessDecisionVoter)
- func (m *AffirmativeBased) Decide(ctx context.Context, authentication authorization.Authentication, ...) error
- func (m *AffirmativeBased) SetAllowIfAllAbstainDecisions(allow bool)
- func (m *AffirmativeBased) Supports(attribute string) bool
- type AnonymousAuthenticationFilter
- type AnonymousAuthenticationProvider
- type AnonymousAuthenticationToken
- type AuthenticatedVoter
- type Authentication
- type AuthenticationEntryPoint
- type AuthenticationManager
- type AuthenticationProvider
- type AuthenticationToken
- type AuthorizeRequests
- type BasicAuthenticationEntryPointWithRealm
- type BasicAuthenticationFilter
- type BasicAuthenticationFilterWithRealm
- type CasbinEnforcer
- type CasbinVoter
- type ConsensusBased
- func (m *ConsensusBased) AddVoter(voter AccessDecisionVoter)
- func (m *ConsensusBased) Decide(ctx context.Context, authentication authorization.Authentication, ...) error
- func (m *ConsensusBased) SetAllowIfAllAbstainDecisions(allow bool)
- func (m *ConsensusBased) SetAllowIfEqualGrantedDenied(allow bool)
- func (m *ConsensusBased) Supports(attribute string) bool
- type CookieClearingLogoutHandler
- type CookieCsrfTokenRepository
- func (r *CookieCsrfTokenRepository) ClearToken(ctx context.Context, request SecurityRequest, response SecurityResponse)
- func (r *CookieCsrfTokenRepository) GenerateToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
- func (r *CookieCsrfTokenRepository) LoadToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
- func (r *CookieCsrfTokenRepository) SaveToken(ctx context.Context, request SecurityRequest, response SecurityResponse, ...)
- func (r *CookieCsrfTokenRepository) ValidateToken(ctx context.Context, request SecurityRequest, token string) bool
- type CorsConfig
- type CorsFilter
- type CsrfAuthenticationStrategy
- type CsrfFilter
- type CsrfToken
- type CsrfTokenManager
- type CsrfTokenRepository
- type DaoAuthenticationProvider
- type DefaultLogoutSuccessHandler
- type DefaultSecurityFilterChain
- type DelegatingPasswordEncoder
- type EnhancedRateLimitFilter
- type EnhancedRateLimitOption
- type ExceptionTranslationFilter
- type ExpressionBasedFilterInvocationSecurityMetadataSource
- type ExpressionInterceptUrlRegistry
- type FilterChainProxy
- type FilterSecurityInterceptor
- func (f *FilterSecurityInterceptor) DoFilter(ctx interface{}, request interface{}, response interface{}, ...) error
- func (f *FilterSecurityInterceptor) Order() int
- func (f *FilterSecurityInterceptor) SetAccessDecisionManager(manager AccessDecisionManager)
- func (f *FilterSecurityInterceptor) SetAuthenticationManager(manager AuthenticationManager)
- func (f *FilterSecurityInterceptor) SetSecurityMetadataSource(source SecurityMetadataSource)
- type FixedWindowCounterRateLimiter
- type GrantedAuthority
- type Http401UnauthorizedEntryPoint
- type Http403ForbiddenAccessDeniedHandler
- type Http403ForbiddenEntryPoint
- type HttpRequestAdapter
- func (a *HttpRequestAdapter) GetAttribute(key string) (any, bool)
- func (a *HttpRequestAdapter) GetHeader(key string) string
- func (a *HttpRequestAdapter) GetMethod() string
- func (a *HttpRequestAdapter) GetURI() string
- func (a *HttpRequestAdapter) RemoteAddress() string
- func (a *HttpRequestAdapter) SetAttribute(key string, value any)
- type HttpResponseAdapter
- type HttpSecurity
- type InMemoryUserDetails
- func (u *InMemoryUserDetails) AccountNonExpired() bool
- func (u *InMemoryUserDetails) AccountNonLocked() bool
- func (u *InMemoryUserDetails) Authorities() []string
- func (u *InMemoryUserDetails) CredentialsNonExpired() bool
- func (u *InMemoryUserDetails) Enabled() bool
- func (u *InMemoryUserDetails) Password() string
- func (u *InMemoryUserDetails) Username() string
- type InMemoryUserDetailsService
- func (s *InMemoryUserDetailsService) CreateUser(username, password string, authorities []string)
- func (s *InMemoryUserDetailsService) DeleteUser(username string)
- func (s *InMemoryUserDetailsService) LoadUserByUsername(ctx context.Context, username string) (UserDetails, error)
- func (s *InMemoryUserDetailsService) UserCount() int
- type LeakyBucketRateLimiter
- type LoginUrlAuthenticationEntryPoint
- type LogoutFilter
- type LogoutHandler
- type LogoutSuccessHandler
- type NoOpPasswordEncoder
- type PasswordEncoder
- type ProviderManager
- type RateLimitConfig
- type RateLimitFilter
- type RateLimitStrategy
- type RateLimiter
- type Role
- type RoleVoter
- type SecurityAutoConfiguration
- type SecurityBuilder
- func (b *SecurityBuilder) AccessDecisionManager(manager AccessDecisionManager) *SecurityBuilder
- func (b *SecurityBuilder) AddFilter(filter SecurityFilter) *SecurityBuilder
- func (b *SecurityBuilder) AddFilterAfter(filter SecurityFilter, after SecurityFilter) *SecurityBuilder
- func (b *SecurityBuilder) AddFilterBefore(filter SecurityFilter, before SecurityFilter) *SecurityBuilder
- func (b *SecurityBuilder) AuthenticationManager(manager AuthenticationManager) *SecurityBuilder
- func (b *SecurityBuilder) Build() SecurityConfig
- func (b *SecurityBuilder) EnableAnonymous() *SecurityBuilder
- func (b *SecurityBuilder) EnableCsrf() *SecurityBuilder
- func (b *SecurityBuilder) EnableFormLogin(processingUrl string, defaultSuccessUrl ...string) *SecurityBuilder
- func (b *SecurityBuilder) EnableHttpBasic() *SecurityBuilder
- func (b *SecurityBuilder) EnableLogout(url string, successHandler ...LogoutSuccessHandler) *SecurityBuilder
- func (b *SecurityBuilder) PasswordEncoder(encoder PasswordEncoder) *SecurityBuilder
- func (b *SecurityBuilder) UserDetailsService(service UserDetailsService) *SecurityBuilder
- type SecurityConfig
- type SecurityContext
- type SecurityContextHolderFilter
- type SecurityContextLogoutHandler
- type SecurityFilter
- type SecurityFilterChain
- type SecurityFilterChainHandler
- type SecurityMetadataSource
- type SecurityRequest
- type SecurityResponse
- type Sha256PasswordEncoderdeprecated
- type SimpleLogoutSuccessHandler
- type SlidingWindowRateLimiter
- type StandardPasswordEncoder
- type StrategyRateLimiterAdapter
- type TokenBucket
- type UnanimousBased
- type UserDetails
- type UserDetailsService
- type UsernamePasswordAuthenticationFilter
- type UsernamePasswordAuthenticationToken
- func (t *UsernamePasswordAuthenticationToken) Authenticated() bool
- func (t *UsernamePasswordAuthenticationToken) Authorities() []string
- func (t *UsernamePasswordAuthenticationToken) Credentials() any
- func (t *UsernamePasswordAuthenticationToken) Name() string
- func (t *UsernamePasswordAuthenticationToken) Principal() any
- func (t *UsernamePasswordAuthenticationToken) SetAuthenticated(authenticated bool)
- func (t *UsernamePasswordAuthenticationToken) SetAuthorities(authorities []string)
- type VirtualFilterChain
- type WebExpressionVoter
- type WebSecurity
Examples ¶
Constants ¶
const ( ACCESS_GRANTED = 1 // 允许访问 ACCESS_DENIED = -1 // 拒绝访问 ACCESS_ABSTAIN = 0 // 投票结果为 abstain 弃权 )
访问决策投票结果常量
const ( // Casbin 配置 CasbinEnabled = "security.casbin.enabled" CasbinModelType = "security.casbin.model-type" CasbinModelPath = "security.casbin.model-path" CasbinModelText = "security.casbin.model-text" CasbinPolicyType = "security.casbin.policy-type" CasbinPolicyPath = "security.casbin.policy-path" CasbinPolicyText = "security.casbin.policy-text" CasbinAutoLoad = "security.casbin.auto-load" CasbinAutoLoadInterval = "security.casbin.auto-load-interval" // casbin 字段常量 CasbinLogFieldModel = "model-path" CasbinLogFieldPolicy = "policy-path" )
const ( DefaultCasbinModelType = "file" DefaultCasbinModelPath = "config/casbin_model.conf" DefaultCasbinPolicyType = "file" DefaultCasbinPolicyPath = "config/casbin_policy.csv" DefaultCasbinAutoLoad = false DefaultCasbinAutoLoadInterval = 5 )
const ( SecurityContextHolderFilterOrder = -1000 AnonymousAuthenticationFilterOrder = 0 ExceptionTranslationFilterOrder = 0 FilterSecurityInterceptorOrder = 100 )
Security filter order constants
const (
ConditionTrue = "true"
)
const DefaultRolePrefix = "ROLE_"
DefaultRolePrefix is the standard prefix prepended to role names.
const (
// Security 配置
SecurityEnabled = "security.enabled"
)
Variables ¶
var ( // ErrAuthenticationFailed 认证失败。 ErrAuthenticationFailed = errors.New("authentication failed") // ErrAccessDenied 访问被拒绝。 ErrAccessDenied = errors.New("access denied") // ErrUserNotFound 用户未找到。 ErrUserNotFound = errors.New("user not found") // ErrBadCredentials 凭证无效。 ErrBadCredentials = errors.New("bad credentials") )
错误定义。
Functions ¶
func ContextWithAuthentication ¶
func ContextWithAuthentication(ctx context.Context, auth Authentication) context.Context
ContextWithAuthentication 将认证信息存入 context.Context。
Types ¶
type AccessDecisionManager ¶
type AccessDecisionManager = authorization.AccessDecisionManager
authorization 包的类型别名
type AccessDecisionVoter ¶
type AccessDecisionVoter = authorization.AccessDecisionVoter
type AccessDeniedHandler ¶
type AccessDeniedHandler interface {
// Handle 处理访问拒绝。
Handle(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
}
AccessDeniedHandler 访问拒绝处理器接口。
处理访问被拒绝的情况,如权限不足。 可以自定义响应格式或重定向到错误页面。
type AffirmativeBased ¶
type AffirmativeBased struct {
// contains filtered or unexported fields
}
AffirmativeBased 肯定优先访问决策管理器
func NewAffirmativeBased ¶
func NewAffirmativeBased(voters ...AccessDecisionVoter) *AffirmativeBased
func (*AffirmativeBased) AddVoter ¶
func (m *AffirmativeBased) AddVoter(voter AccessDecisionVoter)
AddVoter 添加访问决策投票者到决策管理器。
func (*AffirmativeBased) Decide ¶
func (m *AffirmativeBased) Decide(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) error
Decide 决定是否授予访问权限
func (*AffirmativeBased) SetAllowIfAllAbstainDecisions ¶
func (m *AffirmativeBased) SetAllowIfAllAbstainDecisions(allow bool)
SetAllowIfAllAbstainDecisions 设置当所有投票者都弃权时是否允许访问。
func (*AffirmativeBased) Supports ¶ added in v0.0.3
func (m *AffirmativeBased) Supports(attribute string) bool
Supports 是否支持该决策属性
type AnonymousAuthenticationFilter ¶
type AnonymousAuthenticationFilter struct {
// contains filtered or unexported fields
}
AnonymousAuthenticationFilter 匿名认证过滤器
func NewAnonymousAuthenticationFilter ¶
func NewAnonymousAuthenticationFilter() *AnonymousAuthenticationFilter
func (*AnonymousAuthenticationFilter) DoFilter ¶
func (f *AnonymousAuthenticationFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*AnonymousAuthenticationFilter) Order ¶ added in v0.0.3
func (f *AnonymousAuthenticationFilter) Order() int
Order 实现 filter.Filter 接口
type AnonymousAuthenticationProvider ¶
type AnonymousAuthenticationProvider struct{}
AnonymousAuthenticationProvider 匿名认证提供者
func NewAnonymousAuthenticationProvider ¶
func NewAnonymousAuthenticationProvider() *AnonymousAuthenticationProvider
NewAnonymousAuthenticationProvider 创建匿名认证提供者
func (*AnonymousAuthenticationProvider) Authenticate ¶
func (p *AnonymousAuthenticationProvider) Authenticate(ctx context.Context, token AuthenticationToken) (Authentication, error)
Authenticate 为匿名用户创建认证令牌
func (*AnonymousAuthenticationProvider) Supports ¶
func (p *AnonymousAuthenticationProvider) Supports(token AuthenticationToken) bool
Supports 只支持UsernamePasswordAuthenticationToken类型
type AnonymousAuthenticationToken ¶
type AnonymousAuthenticationToken struct {
// contains filtered or unexported fields
}
AnonymousAuthenticationToken 匿名认证令牌
func NewAnonymousAuthenticationToken ¶
func NewAnonymousAuthenticationToken(key string, principal any, authorities []string) *AnonymousAuthenticationToken
func (*AnonymousAuthenticationToken) Authenticated ¶
func (t *AnonymousAuthenticationToken) Authenticated() bool
Authenticated 返回匿名认证是否已通过验证。
func (*AnonymousAuthenticationToken) Authorities ¶
func (t *AnonymousAuthenticationToken) Authorities() []string
Authorities 返回匿名认证的授权列表。
func (*AnonymousAuthenticationToken) Credentials ¶
func (t *AnonymousAuthenticationToken) Credentials() any
Credentials 返回匿名认证的凭据(始终为 nil)。
func (*AnonymousAuthenticationToken) Name ¶
func (t *AnonymousAuthenticationToken) Name() string
Name 返回匿名认证主体的名称字符串。
func (*AnonymousAuthenticationToken) Principal ¶
func (t *AnonymousAuthenticationToken) Principal() any
Principal 返回匿名认证主体的身份信息。
type AuthenticatedVoter ¶
type AuthenticatedVoter struct{}
AuthenticatedVoter 认证投票者
func NewAuthenticatedVoter ¶
func NewAuthenticatedVoter() *AuthenticatedVoter
func (*AuthenticatedVoter) Supports ¶ added in v0.0.3
func (v *AuthenticatedVoter) Supports(attribute string) bool
Supports 是否支持该属性
func (*AuthenticatedVoter) Vote ¶
func (v *AuthenticatedVoter) Vote(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) int
Vote 投票决定访问权限
type Authentication ¶
type Authentication = authentication.Authentication
authentication 包的类型别名
Example ¶
ExampleAuthentication 使用示例:用户认证 展示完整的认证流程
userDetailsService := NewInMemoryUserDetailsService()
userDetailsService.CreateUser("admin", "admin123", []string{"ROLE_ADMIN", "ROLE_USER"})
passwordEncoder := NewNoOpPasswordEncoder()
authProvider := NewDaoAuthenticationProvider(userDetailsService, passwordEncoder, log.Build())
authManager := NewProviderManager(authProvider)
ctx := context.Background()
authToken := NewUsernamePasswordAuthenticationToken("admin", "admin123")
authenticated, err := authManager.Authenticate(ctx, authToken)
if err != nil {
fmt.Printf("Authentication failed: %v\n", err)
return
}
fmt.Printf("Authentication successful!\n")
fmt.Printf("Principal: %v\n", authenticated.Principal())
fmt.Printf("Authorities: %v\n", authenticated.Authorities())
fmt.Printf("Authenticated: %v\n", authenticated.Authenticated())
fmt.Printf("Name: %s\n", extractPrincipalName(authenticated))
func GetAuthenticationFromContext ¶
func GetAuthenticationFromContext(ctx context.Context) Authentication
GetAuthenticationFromContext 从 context.Context 获取认证信息。
type AuthenticationEntryPoint ¶
type AuthenticationEntryPoint interface {
// Commence 开始认证流程。
Commence(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
}
AuthenticationEntryPoint 认证入口点接口。
处理未认证用户访问受保护资源的情况。 通常返回 401 状态码或重定向到登录页面。
type AuthenticationManager ¶
type AuthenticationManager = authentication.AuthenticationManager
type AuthenticationProvider ¶
type AuthenticationProvider = authentication.AuthenticationProvider
type AuthenticationToken ¶ added in v0.0.3
type AuthenticationToken = authentication.AuthenticationToken
type AuthorizeRequests ¶
type AuthorizeRequests interface {
// AntMatchers 配置 Ant 风格的路径匹配器。
AntMatchers(patterns ...string) ExpressionInterceptUrlRegistry
// AnyRequest 配置所有请求。
AnyRequest() ExpressionInterceptUrlRegistry
}
AuthorizeRequests 授权请求配置接口。
配置 URL 路径的访问规则。
type BasicAuthenticationEntryPointWithRealm ¶
type BasicAuthenticationEntryPointWithRealm struct {
// contains filtered or unexported fields
}
BasicAuthenticationEntryPointWithRealm Basic认证入口点(带Realm)
func NewBasicAuthenticationEntryPointWithRealm ¶
func NewBasicAuthenticationEntryPointWithRealm(realmName string, logger log.Logger) *BasicAuthenticationEntryPointWithRealm
func (*BasicAuthenticationEntryPointWithRealm) Commence ¶
func (e *BasicAuthenticationEntryPointWithRealm) Commence(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
Commence 发送 401 Unauthorized 响应并设置 WWW-Authenticate 头为 Basic realm。
type BasicAuthenticationFilter ¶
type BasicAuthenticationFilter struct {
// contains filtered or unexported fields
}
BasicAuthenticationFilter Basic认证过滤器
func NewBasicAuthenticationFilter ¶
func NewBasicAuthenticationFilter(authenticationManager AuthenticationManager) *BasicAuthenticationFilter
func (*BasicAuthenticationFilter) DoFilter ¶
func (f *BasicAuthenticationFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 处理Basic认证
func (*BasicAuthenticationFilter) Order ¶ added in v0.0.3
func (f *BasicAuthenticationFilter) Order() int
Order 实现 filter.Filter 接口
type BasicAuthenticationFilterWithRealm ¶
type BasicAuthenticationFilterWithRealm struct {
// contains filtered or unexported fields
}
BasicAuthenticationFilterWithRealm 带Realm的Basic认证过滤器
func NewBasicAuthenticationFilterWithRealm ¶
func NewBasicAuthenticationFilterWithRealm(authManager AuthenticationManager, realmName string, logger log.Logger) *BasicAuthenticationFilterWithRealm
func (*BasicAuthenticationFilterWithRealm) DoFilter ¶
func (f *BasicAuthenticationFilterWithRealm) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*BasicAuthenticationFilterWithRealm) Order ¶ added in v0.0.3
func (f *BasicAuthenticationFilterWithRealm) Order() int
Order 实现 filter.Filter 接口
type CasbinEnforcer ¶
type CasbinEnforcer interface {
Enforce(ctx context.Context, subject, object, action string) (bool, error)
AddPolicy(ctx context.Context, sub, obj, act string) error
RemovePolicy(ctx context.Context, sub, obj, act string) error
GetPolicy(ctx context.Context) ([][]string, error)
LoadPolicy(ctx context.Context) error
SavePolicy(ctx context.Context) error
}
CasbinEnforcer Casbin 执行器接口。
type CasbinVoter ¶
type CasbinVoter struct {
// contains filtered or unexported fields
}
CasbinVoter Casbin 投票者实现。
func NewCasbinVoter ¶
func NewCasbinVoter(enforcer CasbinEnforcer) *CasbinVoter
func (*CasbinVoter) Supports ¶
func (v *CasbinVoter) Supports(attribute string) bool
Supports 是否支持该属性。
func (*CasbinVoter) Vote ¶
func (v *CasbinVoter) Vote(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) int
Vote 投票决定是否授予访问权限。 resource 格式为 "METHOD:URI"(由 FilterSecurityInterceptor 生成)
type ConsensusBased ¶
type ConsensusBased struct {
// contains filtered or unexported fields
}
ConsensusBased 共识优先访问决策管理器
func NewConsensusBased ¶
func NewConsensusBased(voters ...AccessDecisionVoter) *ConsensusBased
func (*ConsensusBased) AddVoter ¶
func (m *ConsensusBased) AddVoter(voter AccessDecisionVoter)
AddVoter 添加访问决策投票者到决策管理器。
func (*ConsensusBased) Decide ¶
func (m *ConsensusBased) Decide(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) error
Decide 决定是否授予访问权限
func (*ConsensusBased) SetAllowIfAllAbstainDecisions ¶
func (m *ConsensusBased) SetAllowIfAllAbstainDecisions(allow bool)
SetAllowIfAllAbstainDecisions 设置当所有投票者都弃权时是否允许访问。
func (*ConsensusBased) SetAllowIfEqualGrantedDenied ¶
func (m *ConsensusBased) SetAllowIfEqualGrantedDenied(allow bool)
SetAllowIfEqualGrantedDenied 设置当授予和拒绝票数相等时是否允许访问。
func (*ConsensusBased) Supports ¶ added in v0.0.3
func (m *ConsensusBased) Supports(attribute string) bool
Supports 是否支持该决策属性
type CookieClearingLogoutHandler ¶
type CookieClearingLogoutHandler struct {
// contains filtered or unexported fields
}
CookieClearingLogoutHandler Cookie清除登出处理器
func NewCookieClearingLogoutHandler ¶
func NewCookieClearingLogoutHandler(cookieNames ...string) *CookieClearingLogoutHandler
func (*CookieClearingLogoutHandler) Logout ¶
func (h *CookieClearingLogoutHandler) Logout(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
type CookieCsrfTokenRepository ¶
type CookieCsrfTokenRepository struct {
// contains filtered or unexported fields
}
CookieCsrfTokenRepository 基于Cookie的CSRF令牌仓库
func NewCookieCsrfTokenRepository ¶
func NewCookieCsrfTokenRepository() *CookieCsrfTokenRepository
func (*CookieCsrfTokenRepository) ClearToken ¶
func (r *CookieCsrfTokenRepository) ClearToken(ctx context.Context, request SecurityRequest, response SecurityResponse)
func (*CookieCsrfTokenRepository) GenerateToken ¶
func (r *CookieCsrfTokenRepository) GenerateToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
func (*CookieCsrfTokenRepository) LoadToken ¶ added in v0.0.4
func (r *CookieCsrfTokenRepository) LoadToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
LoadToken 从 Cookie 中加载已存在的 CSRF 令牌,未找到时返回 nil。
func (*CookieCsrfTokenRepository) SaveToken ¶
func (r *CookieCsrfTokenRepository) SaveToken(ctx context.Context, request SecurityRequest, response SecurityResponse, token *CsrfToken)
func (*CookieCsrfTokenRepository) ValidateToken ¶
func (r *CookieCsrfTokenRepository) ValidateToken(ctx context.Context, request SecurityRequest, token string) bool
type CorsConfig ¶
type CorsConfig struct {
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
MaxAge int
Log log.Logger
}
CorsConfig CORS配置
type CorsFilter ¶
type CorsFilter struct {
// contains filtered or unexported fields
}
CorsFilter CORS过滤器
func NewCorsFilter ¶
func NewCorsFilter(config CorsConfig) *CorsFilter
func (*CorsFilter) DoFilter ¶
func (f *CorsFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*CorsFilter) Order ¶ added in v0.0.3
func (f *CorsFilter) Order() int
Order 实现 filter.Filter 接口
type CsrfAuthenticationStrategy ¶
type CsrfAuthenticationStrategy struct {
// contains filtered or unexported fields
}
CsrfAuthenticationStrategy CSRF 令牌会话认证策略
func NewCsrfAuthenticationStrategy ¶
func NewCsrfAuthenticationStrategy() *CsrfAuthenticationStrategy
func (*CsrfAuthenticationStrategy) OnAuthentication ¶
func (s *CsrfAuthenticationStrategy) OnAuthentication(ctx context.Context, authentication Authentication, request SecurityRequest, response SecurityResponse)
OnAuthentication 认证成功后生成新的 CSRF 令牌
type CsrfFilter ¶
type CsrfFilter struct {
// contains filtered or unexported fields
}
CsrfFilter CSRF防护过滤器。
在表单提交时验证 CSRF Token,防止跨站请求伪造攻击。
func NewCsrfFilter ¶
func NewCsrfFilter(tokenRepository CsrfTokenRepository) *CsrfFilter
NewCsrfFilter 创建 CSRF 防护过滤器。
参数:
- tokenRepository: CSRF Token 存储仓库,用于生成和验证 Token
返回:
- *CsrfFilter: CSRF 过滤器实例
panic: tokenRepository 为 nil 时触发 panic
func (*CsrfFilter) AddExcludePath ¶
func (f *CsrfFilter) AddExcludePath(paths ...string) error
AddExcludePath 添加不需要 CSRF 防护的路径。
参数:
- paths: 要排除的路径列表,必须以 "/" 开头
返回:
- error: 路径格式错误时返回错误
func (*CsrfFilter) DoFilter ¶
func (f *CsrfFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*CsrfFilter) Order ¶ added in v0.0.3
func (f *CsrfFilter) Order() int
Order 实现 filter.Filter 接口
type CsrfTokenManager ¶
type CsrfTokenManager struct {
// contains filtered or unexported fields
}
CsrfTokenManager CSRF 令牌管理器
func NewCsrfTokenManager ¶
func NewCsrfTokenManager() *CsrfTokenManager
func (*CsrfTokenManager) GenerateToken ¶
func (m *CsrfTokenManager) GenerateToken(principal string) (string, error)
func (*CsrfTokenManager) RemoveToken ¶
func (m *CsrfTokenManager) RemoveToken(principal string)
func (*CsrfTokenManager) ValidateToken ¶
func (m *CsrfTokenManager) ValidateToken(principal, token string) bool
type CsrfTokenRepository ¶
type CsrfTokenRepository interface {
// GenerateToken 生成新的 CSRF 令牌。
GenerateToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
// LoadToken 加载当前会话已存在的 CSRF 令牌,会话中不存在时返回 nil。
LoadToken(ctx context.Context, request SecurityRequest) (*CsrfToken, error)
// ValidateToken 验证 CSRF 令牌。
ValidateToken(ctx context.Context, request SecurityRequest, token string) bool
// SaveToken 保存 CSRF 令牌到响应。
SaveToken(ctx context.Context, request SecurityRequest, response SecurityResponse, token *CsrfToken)
// ClearToken 清除 CSRF 令牌。
ClearToken(ctx context.Context, request SecurityRequest, response SecurityResponse)
}
CsrfTokenRepository CSRF 令牌仓库接口。
管理 CSRF 令牌的生成、验证、保存和清除。
type DaoAuthenticationProvider ¶
type DaoAuthenticationProvider struct {
// contains filtered or unexported fields
}
DaoAuthenticationProvider 基于DAO的认证提供者
func NewDaoAuthenticationProvider ¶
func NewDaoAuthenticationProvider(userDetailsService UserDetailsService, passwordEncoder PasswordEncoder, logger log.Logger) *DaoAuthenticationProvider
NewDaoAuthenticationProvider 创建DAO认证提供者
func (*DaoAuthenticationProvider) Authenticate ¶
func (p *DaoAuthenticationProvider) Authenticate(ctx context.Context, token AuthenticationToken) (Authentication, error)
Authenticate 执行认证逻辑
func (*DaoAuthenticationProvider) Supports ¶
func (p *DaoAuthenticationProvider) Supports(token AuthenticationToken) bool
Supports 判断是否支持该认证方式
type DefaultLogoutSuccessHandler ¶
type DefaultLogoutSuccessHandler struct {
// contains filtered or unexported fields
}
DefaultLogoutSuccessHandler 默认登出成功处理器
func NewDefaultLogoutSuccessHandler ¶
func NewDefaultLogoutSuccessHandler(defaultTargetUrl string) *DefaultLogoutSuccessHandler
func (*DefaultLogoutSuccessHandler) OnLogoutSuccess ¶
func (h *DefaultLogoutSuccessHandler) OnLogoutSuccess(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
type DefaultSecurityFilterChain ¶
type DefaultSecurityFilterChain struct{}
DefaultSecurityFilterChain 默认安全过滤器链
func (*DefaultSecurityFilterChain) DoFilter ¶
func (c *DefaultSecurityFilterChain) DoFilter(ctx interface{}, request interface{}, response interface{}) error
DoFilter 实现 filter.SecurityFilterChain 接口,默认空操作。
func (*DefaultSecurityFilterChain) GetFilters ¶ added in v0.0.3
func (c *DefaultSecurityFilterChain) GetFilters() []SecurityFilter
GetFilters 返回该过滤器链中的所有安全过滤器(默认返回空)。
func (*DefaultSecurityFilterChain) Matches ¶ added in v0.0.3
func (c *DefaultSecurityFilterChain) Matches(request interface{}) bool
Matches 实现 filter.SecurityFilterChain 接口,默认匹配所有请求。
type DelegatingPasswordEncoder ¶
type DelegatingPasswordEncoder struct {
// contains filtered or unexported fields
}
DelegatingPasswordEncoder 委托密码编码器 职责:支持多种编码器,可根据编码ID选择合适的编码器 编码格式:{编码器ID}encodedPassword,例如:{bcrypt}$2a$10$... 优势:支持密码编码算法迁移,历史密码无需重新编码
func NewDelegatingPasswordEncoder ¶
func NewDelegatingPasswordEncoder(idForEncode string, passwordEncoders map[string]PasswordEncoder) *DelegatingPasswordEncoder
NewDelegatingPasswordEncoder 创建委托密码编码器 idForEncode: 默认使用的编码器ID passwordEncoders: 可用的编码器映射
func (*DelegatingPasswordEncoder) Encode ¶
func (e *DelegatingPasswordEncoder) Encode(rawPassword string) string
Encode 使用默认编码器编码密码
func (*DelegatingPasswordEncoder) Matches ¶
func (e *DelegatingPasswordEncoder) Matches(rawPassword, encodedPassword string) bool
Matches 根据编码ID选择合适的编码器进行匹配
type EnhancedRateLimitFilter ¶
type EnhancedRateLimitFilter struct {
// contains filtered or unexported fields
}
EnhancedRateLimitFilter 增强版限流过滤器
func NewEnhancedRateLimitFilter ¶
func NewEnhancedRateLimitFilter(strategy RateLimitStrategy, opts ...EnhancedRateLimitOption) *EnhancedRateLimitFilter
func (*EnhancedRateLimitFilter) DoFilter ¶
func (f *EnhancedRateLimitFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*EnhancedRateLimitFilter) Order ¶ added in v0.0.3
func (f *EnhancedRateLimitFilter) Order() int
Order 实现 filter.Filter 接口
type EnhancedRateLimitOption ¶
type EnhancedRateLimitOption func(*EnhancedRateLimitFilter)
func WithExcludePaths ¶
func WithExcludePaths(paths ...string) EnhancedRateLimitOption
func WithOnRateLimit ¶
func WithOnRateLimit(fn func(ctx context.Context, request SecurityRequest, response SecurityResponse)) EnhancedRateLimitOption
func WithTrustedProxies ¶ added in v0.0.4
func WithTrustedProxies(proxies ...string) EnhancedRateLimitOption
WithTrustedProxies 设置可信代理 IP/CIDR 列表。 启用后仅信任来自这些代理的转发头,防止客户端伪造 IP 绕过限流。
type ExceptionTranslationFilter ¶
type ExceptionTranslationFilter struct {
// contains filtered or unexported fields
}
ExceptionTranslationFilter 异常转换过滤器
func NewExceptionTranslationFilter ¶
func NewExceptionTranslationFilter(accessDeniedHandler AccessDeniedHandler, authenticationEntryPoint AuthenticationEntryPoint) *ExceptionTranslationFilter
func (*ExceptionTranslationFilter) DoFilter ¶
func (f *ExceptionTranslationFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*ExceptionTranslationFilter) Order ¶ added in v0.0.3
func (f *ExceptionTranslationFilter) Order() int
Order 实现 filter.Filter 接口
type ExpressionBasedFilterInvocationSecurityMetadataSource ¶
type ExpressionBasedFilterInvocationSecurityMetadataSource struct {
// contains filtered or unexported fields
}
ExpressionBasedFilterInvocationSecurityMetadataSource 基于表达式的过滤器调用安全元数据源
func NewExpressionBasedFilterInvocationSecurityMetadataSource ¶
func NewExpressionBasedFilterInvocationSecurityMetadataSource() *ExpressionBasedFilterInvocationSecurityMetadataSource
NewExpressionBasedFilterInvocationSecurityMetadataSource 创建基于表达式的过滤器调用安全元数据源实例。
func (*ExpressionBasedFilterInvocationSecurityMetadataSource) AddMapping ¶
func (s *ExpressionBasedFilterInvocationSecurityMetadataSource) AddMapping(pattern string, attributes []string)
AddMapping 添加 URL 模式与安全属性的映射关系。
func (*ExpressionBasedFilterInvocationSecurityMetadataSource) GetAttributes ¶
func (s *ExpressionBasedFilterInvocationSecurityMetadataSource) GetAttributes(ctx context.Context, request SecurityRequest) ([]string, error)
GetAttributes 根据请求获取匹配的安全属性列表。
type ExpressionInterceptUrlRegistry ¶
type ExpressionInterceptUrlRegistry interface {
// PermitAll 允许所有访问。
PermitAll() HttpSecurity
// Authenticated 需要认证。
Authenticated() HttpSecurity
// HasRole 需要指定角色。
HasRole(role string) HttpSecurity
// HasAnyRole 需要指定角色之一。
HasAnyRole(roles ...string) HttpSecurity
// HasAuthority 需要指定权限。
HasAuthority(authority string) HttpSecurity
// HasAnyAuthority 需要指定权限之一。
HasAnyAuthority(authorities ...string) HttpSecurity
// DenyAll 拒绝所有访问。
DenyAll() HttpSecurity
}
ExpressionInterceptUrlRegistry URL 拦截注册接口。
配置特定 URL 的访问表达式。
type FilterChainProxy ¶
type FilterChainProxy struct {
// contains filtered or unexported fields
}
FilterChainProxy 过滤器链代理
func NewFilterChainProxy ¶
func NewFilterChainProxy(filters []SecurityFilter, chain SecurityFilterChain) *FilterChainProxy
NewFilterChainProxy 创建过滤器链代理实例。
参数:
- filters: 安全过滤器列表
- chain: 最终的安全过滤器链
func (*FilterChainProxy) DoFilter ¶
func (p *FilterChainProxy) DoFilter(ctx interface{}, request interface{}, response interface{}) error
DoFilter 实现 filter.SecurityFilterChain 接口
func (*FilterChainProxy) GetFilters ¶ added in v0.0.3
func (p *FilterChainProxy) GetFilters() []filter.Filter
GetFilters 实现 filter.SecurityFilterChain 接口
func (*FilterChainProxy) Matches ¶ added in v0.0.3
func (p *FilterChainProxy) Matches(request interface{}) bool
Matches 实现 filter.SecurityFilterChain 接口(FilterChainProxy 匹配所有请求)
type FilterSecurityInterceptor ¶
type FilterSecurityInterceptor struct {
// contains filtered or unexported fields
}
FilterSecurityInterceptor 过滤器安全拦截器
func NewFilterSecurityInterceptor ¶
func NewFilterSecurityInterceptor(securityMetadataSource SecurityMetadataSource, accessDecisionManager AccessDecisionManager, authenticationManager AuthenticationManager) *FilterSecurityInterceptor
func (*FilterSecurityInterceptor) DoFilter ¶
func (f *FilterSecurityInterceptor) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*FilterSecurityInterceptor) Order ¶ added in v0.0.3
func (f *FilterSecurityInterceptor) Order() int
Order 实现 filter.Filter 接口
func (*FilterSecurityInterceptor) SetAccessDecisionManager ¶
func (f *FilterSecurityInterceptor) SetAccessDecisionManager(manager AccessDecisionManager)
SetAccessDecisionManager 设置访问决策管理器。
func (*FilterSecurityInterceptor) SetAuthenticationManager ¶
func (f *FilterSecurityInterceptor) SetAuthenticationManager(manager AuthenticationManager)
SetAuthenticationManager 设置认证管理器。
func (*FilterSecurityInterceptor) SetSecurityMetadataSource ¶
func (f *FilterSecurityInterceptor) SetSecurityMetadataSource(source SecurityMetadataSource)
SetSecurityMetadataSource 设置安全元数据源。
type FixedWindowCounterRateLimiter ¶
type FixedWindowCounterRateLimiter struct {
// contains filtered or unexported fields
}
FixedWindowCounterRateLimiter 固定窗口计数器限流器
func NewFixedWindowCounterRateLimiter ¶
func NewFixedWindowCounterRateLimiter(windowSize time.Duration, maxRequests int) *FixedWindowCounterRateLimiter
func (*FixedWindowCounterRateLimiter) Allow ¶
func (r *FixedWindowCounterRateLimiter) Allow(key string) bool
Allow 检查指定 key 的请求是否允许通过(固定窗口计数算法)。
func (*FixedWindowCounterRateLimiter) Cleanup ¶
func (r *FixedWindowCounterRateLimiter) Cleanup()
Cleanup 清理固定窗口中过期的计数器数据,释放内存。
func (*FixedWindowCounterRateLimiter) Close ¶ added in v0.0.4
func (r *FixedWindowCounterRateLimiter) Close()
Close 关闭固定窗口计数器限流器,停止后台清理协程。
type GrantedAuthority ¶
type GrantedAuthority interface {
// Authority 返回权限字符串。
Authority() string
}
GrantedAuthority 授予权限接口。
代表一个具体的权限,如 "ROLE_ADMIN"、"ROLE_USER"。
func NewAuthority ¶
func NewAuthority(authority string) GrantedAuthority
NewAuthority 创建权限(GrantedAuthority接口)
type Http401UnauthorizedEntryPoint ¶
type Http401UnauthorizedEntryPoint struct{}
Http401UnauthorizedEntryPoint 401未认证入口点
func NewHttp401UnauthorizedEntryPoint ¶
func NewHttp401UnauthorizedEntryPoint() *Http401UnauthorizedEntryPoint
func (*Http401UnauthorizedEntryPoint) Commence ¶
func (e *Http401UnauthorizedEntryPoint) Commence(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
Commence 发送 401 Unauthorized 响应给客户端。
type Http403ForbiddenAccessDeniedHandler ¶
type Http403ForbiddenAccessDeniedHandler struct{}
Http403ForbiddenAccessDeniedHandler 403禁止访问拒绝处理器
func NewHttp403ForbiddenAccessDeniedHandler ¶
func NewHttp403ForbiddenAccessDeniedHandler() *Http403ForbiddenAccessDeniedHandler
func (*Http403ForbiddenAccessDeniedHandler) Handle ¶
func (e *Http403ForbiddenAccessDeniedHandler) Handle(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
Handle 处理访问被拒绝的情况,发送 403 Forbidden 响应给客户端。
type Http403ForbiddenEntryPoint ¶
type Http403ForbiddenEntryPoint struct{}
Http403ForbiddenEntryPoint 403禁止访问入口点
func NewHttp403ForbiddenEntryPoint ¶
func NewHttp403ForbiddenEntryPoint() *Http403ForbiddenEntryPoint
func (*Http403ForbiddenEntryPoint) Commence ¶
func (e *Http403ForbiddenEntryPoint) Commence(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
Commence 发送 403 Forbidden 响应给客户端。
type HttpRequestAdapter ¶
type HttpRequestAdapter struct {
// contains filtered or unexported fields
}
HttpRequestAdapter HTTP请求适配器
func NewHttpRequestAdapter ¶
func NewHttpRequestAdapter(request *http.Request) *HttpRequestAdapter
func (*HttpRequestAdapter) GetAttribute ¶
func (a *HttpRequestAdapter) GetAttribute(key string) (any, bool)
GetAttribute 获取请求上下文的指定属性值。
func (*HttpRequestAdapter) GetHeader ¶
func (a *HttpRequestAdapter) GetHeader(key string) string
GetHeader 返回 HTTP 请求头的指定键对应的值。
func (*HttpRequestAdapter) GetMethod ¶
func (a *HttpRequestAdapter) GetMethod() string
GetMethod 返回 HTTP 请求方法(GET、POST 等)。
func (*HttpRequestAdapter) GetURI ¶
func (a *HttpRequestAdapter) GetURI() string
GetURI 返回 HTTP 请求的 URI 路径。
func (*HttpRequestAdapter) RemoteAddress ¶ added in v0.0.4
func (a *HttpRequestAdapter) RemoteAddress() string
RemoteAddress 返回直连对端的地址。
func (*HttpRequestAdapter) SetAttribute ¶
func (a *HttpRequestAdapter) SetAttribute(key string, value any)
SetAttribute 设置请求上下文的属性键值对。
type HttpResponseAdapter ¶
type HttpResponseAdapter struct {
// contains filtered or unexported fields
}
HttpResponseAdapter HTTP响应适配器
func NewHttpResponseAdapter ¶
func NewHttpResponseAdapter(responseWriter http.ResponseWriter) *HttpResponseAdapter
func (*HttpResponseAdapter) SetHeader ¶
func (a *HttpResponseAdapter) SetHeader(key, value string)
SetHeader 设置 HTTP 响应头的指定键值对。
func (*HttpResponseAdapter) SetStatusCode ¶
func (a *HttpResponseAdapter) SetStatusCode(code int)
SetStatusCode 设置 HTTP 响应状态码。
WriteHeader 延迟到首次写入响应体时提交,确保 SetStatusCode 之后设置的 响应头仍能生效(net/http 中 WriteHeader 之后再修改 Header 无效)。
func (*HttpResponseAdapter) StatusCode ¶
func (a *HttpResponseAdapter) StatusCode() int
StatusCode 返回已设置的 HTTP 响应状态码。
func (*HttpResponseAdapter) Write ¶
func (a *HttpResponseAdapter) Write(data []byte) error
Write 写入 HTTP 响应体数据。
type HttpSecurity ¶
type HttpSecurity interface {
// AuthenticationManager 设置认证管理器。
AuthenticationManager(authManager AuthenticationManager) HttpSecurity
// UserDetailsService 设置用户详情服务。
UserDetailsService(userDetailsService UserDetailsService) HttpSecurity
// PasswordEncoder 设置密码编码器。
PasswordEncoder(encoder PasswordEncoder) HttpSecurity
// AccessDecisionManager 设置访问决策管理器。
AccessDecisionManager(manager AccessDecisionManager) HttpSecurity
// SecurityMetadataSource 设置安全元数据源。
SecurityMetadataSource(source SecurityMetadataSource) HttpSecurity
// AuthorizeRequests 配置授权规则。
AuthorizeRequests(config func(authorizer AuthorizeRequests)) HttpSecurity
// AddFilter 添加过滤器。
AddFilter(filter SecurityFilter) HttpSecurity
// AddFilterBefore 在指定过滤器之前添加过滤器。
AddFilterBefore(filter SecurityFilter, beforeFilter SecurityFilter) HttpSecurity
// AddFilterAfter 在指定过滤器之后添加过滤器。
AddFilterAfter(filter SecurityFilter, afterFilter SecurityFilter) HttpSecurity
// Anonymous 启用匿名访问。
Anonymous() HttpSecurity
// ExceptionHandling 配置异常处理。
ExceptionHandling(handler AccessDeniedHandler, entryPoint AuthenticationEntryPoint) HttpSecurity
// Csrf 启用 CSRF 防护。
Csrf() HttpSecurity
// Logout 配置登出。
Logout(logoutUrl string, successHandler ...LogoutSuccessHandler) HttpSecurity
// FormLogin 配置表单登录。
FormLogin(loginProcessingUrl string, defaultSuccessUrl ...string) HttpSecurity
// HttpBasic 启用 HTTP Basic 认证。
HttpBasic() HttpSecurity
// Build 构建安全过滤器链。
Build() (SecurityFilterChain, error)
}
HttpSecurity HTTP 安全配置接口。
提供链式 API 配置 HTTP 安全规则。 支持认证管理器、用户详情服务、过滤器、CSRF、登出等配置。
注意:此接口有 16 个方法,违反小接口原则。 未来版本将拆分为多个独立的 Configurer 接口(CsrfConfigurer、CorsConfigurer 等)。
使用示例:
httpSec := security.NewHttpSecurity()
httpSec.FormLogin("/login").
Logout("/logout").
Csrf().
AuthorizeRequests(func(authz security.AuthorizeRequests) {
authz.AntMatchers("/api/**").HasRole("ROLE_API")
authz.AnyRequest().Authenticated()
})
Example ¶
ExampleHttpSecurity 使用示例:HTTP安全配置 展示链式API配置HTTP安全规则
userDetailsService := NewInMemoryUserDetailsService()
userDetailsService.CreateUser("admin", "admin123", []string{"ROLE_ADMIN"})
userDetailsService.CreateUser("user", "user123", []string{"ROLE_USER"})
passwordEncoder := NewNoOpPasswordEncoder()
authProvider := NewDaoAuthenticationProvider(userDetailsService, passwordEncoder, log.Build())
authManager := NewProviderManager(authProvider)
metadataSource := NewExpressionBasedFilterInvocationSecurityMetadataSource()
metadataSource.AddMapping("/public/**", []string{"permitAll"})
metadataSource.AddMapping("/admin/**", []string{"hasRole('ADMIN')"})
metadataSource.AddMapping("/api/**", []string{"authenticated"})
httpSecurity := NewHttpSecurity()
httpSecurity.
AuthenticationManager(authManager).
SecurityMetadataSource(metadataSource)
chain, err := httpSecurity.Build()
if err != nil {
fmt.Printf("Failed to build: %v\n", err)
return
}
fmt.Printf("Security chain built successfully: %v\n", chain != nil)
func NewHttpSecurity ¶
func NewHttpSecurity() HttpSecurity
NewHttpSecurity 创建 HTTP 安全配置构建器。
返回:
- HttpSecurity: 安全配置构建器实例,支持链式调用配置安全策略
type InMemoryUserDetails ¶
type InMemoryUserDetails struct {
// contains filtered or unexported fields
}
InMemoryUserDetails 内存用户详情实现 存储用户的完整认证和授权信息,包括: - 用户名和密码 - 权限列表(角色和权限) - 账户状态(是否启用、是否过期、是否锁定)
func NewInMemoryUserDetails ¶
func NewInMemoryUserDetails(username, password string, authorities []string) *InMemoryUserDetails
NewInMemoryUserDetails 创建内存用户详情 默认值: enabled=true, accountNonExpired=true, credentialsNonExpired=true, accountNonLocked=true
func (*InMemoryUserDetails) AccountNonExpired ¶
func (u *InMemoryUserDetails) AccountNonExpired() bool
AccountNonExpired 返回账户是否未过期
func (*InMemoryUserDetails) AccountNonLocked ¶
func (u *InMemoryUserDetails) AccountNonLocked() bool
AccountNonLocked 返回账户是否未锁定
func (*InMemoryUserDetails) Authorities ¶
func (u *InMemoryUserDetails) Authorities() []string
Authorities 返回授权列表
func (*InMemoryUserDetails) CredentialsNonExpired ¶
func (u *InMemoryUserDetails) CredentialsNonExpired() bool
CredentialsNonExpired 返回凭证是否未过期
func (*InMemoryUserDetails) Password ¶
func (u *InMemoryUserDetails) Password() string
Password 返回密码
func (*InMemoryUserDetails) Username ¶
func (u *InMemoryUserDetails) Username() string
Username 返回用户名
type InMemoryUserDetailsService ¶
type InMemoryUserDetailsService struct {
// contains filtered or unexported fields
}
InMemoryUserDetailsService 内存用户详情服务 使用内存map存储用户信息,线程安全 适用场景:开发和测试环境,生产环境应使用数据库实现
func NewInMemoryUserDetailsService ¶
func NewInMemoryUserDetailsService() *InMemoryUserDetailsService
NewInMemoryUserDetailsService 创建内存用户详情服务
func (*InMemoryUserDetailsService) CreateUser ¶
func (s *InMemoryUserDetailsService) CreateUser(username, password string, authorities []string)
CreateUser 创建新用户
func (*InMemoryUserDetailsService) DeleteUser ¶
func (s *InMemoryUserDetailsService) DeleteUser(username string)
DeleteUser 删除用户
func (*InMemoryUserDetailsService) LoadUserByUsername ¶
func (s *InMemoryUserDetailsService) LoadUserByUsername(ctx context.Context, username string) (UserDetails, error)
LoadUserByUsername 根据用户名加载用户 如果用户不存在返回ErrUserNotFound
func (*InMemoryUserDetailsService) UserCount ¶
func (s *InMemoryUserDetailsService) UserCount() int
UserCount 返回用户总数
type LeakyBucketRateLimiter ¶
type LeakyBucketRateLimiter struct {
// contains filtered or unexported fields
}
LeakyBucketRateLimiter 漏桶限流器
func NewLeakyBucketRateLimiter ¶
func NewLeakyBucketRateLimiter(capacity int, rate time.Duration) *LeakyBucketRateLimiter
func (*LeakyBucketRateLimiter) Allow ¶
func (r *LeakyBucketRateLimiter) Allow(key string) bool
Allow 检查指定 key 的请求是否允许通过(漏桶算法)。
func (*LeakyBucketRateLimiter) Cleanup ¶
func (r *LeakyBucketRateLimiter) Cleanup()
Cleanup 清理漏桶中过期的桶数据,释放内存。
func (*LeakyBucketRateLimiter) Close ¶ added in v0.0.4
func (r *LeakyBucketRateLimiter) Close()
Close 关闭漏桶限流器,停止后台清理协程。
type LoginUrlAuthenticationEntryPoint ¶
type LoginUrlAuthenticationEntryPoint struct {
// contains filtered or unexported fields
}
LoginUrlAuthenticationEntryPoint 登录URL认证入口点
func NewLoginUrlAuthenticationEntryPoint ¶
func NewLoginUrlAuthenticationEntryPoint(loginFormUrl string) *LoginUrlAuthenticationEntryPoint
func (*LoginUrlAuthenticationEntryPoint) Commence ¶
func (e *LoginUrlAuthenticationEntryPoint) Commence(ctx context.Context, request SecurityRequest, response SecurityResponse, err error) error
Commence 重定向客户端到登录页面。
type LogoutFilter ¶
type LogoutFilter struct {
// contains filtered or unexported fields
}
LogoutFilter 登出过滤器。
处理用户登出请求,支持自定义登出 URL 和登出处理器。
func NewLogoutFilter ¶
func NewLogoutFilter(logoutUrl string, handlers []LogoutHandler) *LogoutFilter
NewLogoutFilter 创建登出过滤器。
参数:
- logoutUrl: 登出 URL 路径,必须以 "/" 开头
- handlers: 登出处理器列表,可为 nil
返回:
- *LogoutFilter: 登出过滤器实例
panic: logoutUrl 为空时触发 panic
func (*LogoutFilter) AddLogoutHandler ¶
func (f *LogoutFilter) AddLogoutHandler(handler LogoutHandler)
func (*LogoutFilter) DoFilter ¶
func (f *LogoutFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*LogoutFilter) Order ¶ added in v0.0.3
func (f *LogoutFilter) Order() int
Order 实现 filter.Filter 接口
func (*LogoutFilter) SetSuccessHandler ¶
func (f *LogoutFilter) SetSuccessHandler(handler LogoutSuccessHandler)
type LogoutHandler ¶
type LogoutHandler interface {
// Logout 处理登出。
Logout(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
}
LogoutHandler 登出处理器接口。
type LogoutSuccessHandler ¶
type LogoutSuccessHandler interface {
// OnLogoutSuccess 处理登出成功。
OnLogoutSuccess(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
}
LogoutSuccessHandler 登出成功处理器接口。
type NoOpPasswordEncoder ¶
type NoOpPasswordEncoder struct{}
NoOpPasswordEncoder 不进行编码的密码编码器 适用场景:仅用于开发和测试环境,明文存储密码 警告:生产环境绝对不要使用此编码器
func NewNoOpPasswordEncoder ¶
func NewNoOpPasswordEncoder() *NoOpPasswordEncoder
NewNoOpPasswordEncoder 创建NoOp密码编码器
func (*NoOpPasswordEncoder) Encode ¶
func (e *NoOpPasswordEncoder) Encode(rawPassword string) string
Encode 直接返回原始密码
func (*NoOpPasswordEncoder) Matches ¶
func (e *NoOpPasswordEncoder) Matches(rawPassword, encodedPassword string) bool
Matches 直接比较原始密码和编码后密码
type PasswordEncoder ¶
type PasswordEncoder = authentication.PasswordEncoder
Example ¶
ExamplePasswordEncoder 使用示例:密码编码 展示不同密码编码器的使用
noop := NewNoOpPasswordEncoder()
encoded := noop.Encode("secret")
fmt.Printf("NoOp encoded: %s\n", encoded)
fmt.Printf("NoOp matches: %v\n", noop.Matches("secret", encoded))
sha256 := NewSha256PasswordEncoder()
encoded = sha256.Encode("secret")
fmt.Printf("SHA256 encoded: %s\n", encoded[:20]+"...")
fmt.Printf("SHA256 matches: %v\n", sha256.Matches("secret", encoded))
standard := NewStandardPasswordEncoder("mysecret")
encoded = standard.Encode("secret")
fmt.Printf("Standard encoded: %s\n", encoded[:20]+"...")
fmt.Printf("Standard matches: %v\n", standard.Matches("secret", encoded))
type ProviderManager ¶
type ProviderManager struct {
// contains filtered or unexported fields
}
ProviderManager 认证提供者管理器
func NewProviderManager ¶
func NewProviderManager(providers ...AuthenticationProvider) *ProviderManager
NewProviderManager 创建认证提供者管理器
func (*ProviderManager) AddProvider ¶
func (m *ProviderManager) AddProvider(provider AuthenticationProvider)
AddProvider 添加认证提供者
func (*ProviderManager) Authenticate ¶
func (m *ProviderManager) Authenticate(ctx context.Context, token AuthenticationToken) (Authentication, error)
Authenticate 尝试通过配置的提供者进行认证
type RateLimitConfig ¶
type RateLimitConfig struct {
Enabled bool
Rate int
Burst int
ExcludePaths []string
Log log.Logger
TrustProxyHeaders bool // 是否信任 X-Forwarded-For 等代理头
TrustedProxies []string // 可信代理 IP 或 CIDR 列表,仅从这些代理获取真实客户端 IP
BucketIdleTimeout time.Duration // 空闲桶清理超时,防止内存泄漏
CleanupInterval time.Duration // 过期桶清理周期
}
RateLimitConfig 限流配置
type RateLimitFilter ¶
type RateLimitFilter struct {
// contains filtered or unexported fields
}
RateLimitFilter 限流过滤器
func NewRateLimitFilter ¶
func NewRateLimitFilter(config RateLimitConfig) *RateLimitFilter
func (*RateLimitFilter) DoFilter ¶
func (f *RateLimitFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*RateLimitFilter) Order ¶ added in v0.0.3
func (f *RateLimitFilter) Order() int
Order 实现 filter.Filter 接口
type RateLimitStrategy ¶
RateLimitStrategy 限流策略接口。
type RateLimiter ¶
type RateLimiter interface {
// Allow 判断是否允许请求。
Allow(key string) bool
// Cleanup 清理过期数据。
Cleanup()
}
RateLimiter 限流器接口。
提供请求频率限制功能,防止恶意请求和暴力攻击。
type Role ¶
type Role struct {
// contains filtered or unexported fields
}
Role 角色实现 实现GrantedAuthority接口
type RoleVoter ¶
type RoleVoter struct {
// contains filtered or unexported fields
}
RoleVoter 角色投票者
func NewRoleVoter ¶
func NewRoleVoter() *RoleVoter
func (*RoleVoter) SetRolePrefix ¶
SetRolePrefix 设置角色前缀(默认为 ROLE_)。
func (*RoleVoter) Vote ¶
func (v *RoleVoter) Vote(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) int
Vote 投票决定访问权限
type SecurityAutoConfiguration ¶
type SecurityAutoConfiguration struct {
// contains filtered or unexported fields
}
SecurityAutoConfiguration 安全模块自动配置 当 security.enabled=true 时自动装配以下组件: - UserDetailsService: 默认使用内存存储(可自定义) - PasswordEncoder: 默认使用NoOp编码器(生产环境应使用BCrypt) - AuthenticationManager: 包含DaoAuthenticationProvider和AnonymousAuthenticationProvider - SecurityFilterChain: 默认安全过滤器链(支持CORS、限流、JWT等)
自动配置流程: 1. 检查容器是否已有UserDetailsService,没有则创建默认的InMemoryUserDetailsService 2. 检查容器是否已有PasswordEncoder,没有则创建NoOpPasswordEncoder 3. 构建AuthenticationManager(包含DAO认证提供者和匿名认证提供者) 4. 构建SecurityFilterChain(包含CORS、限流、认证、授权等过滤器) 5. 将组件注册到容器中
func (*SecurityAutoConfiguration) Configure ¶
func (c *SecurityAutoConfiguration) Configure(ctx boot.ApplicationContext) error
Configure 执行自动配置
type SecurityBuilder ¶
type SecurityBuilder struct {
// contains filtered or unexported fields
}
SecurityBuilder 安全配置构建器
func (*SecurityBuilder) AccessDecisionManager ¶
func (b *SecurityBuilder) AccessDecisionManager(manager AccessDecisionManager) *SecurityBuilder
AccessDecisionManager 设置访问决策管理器
func (*SecurityBuilder) AddFilter ¶
func (b *SecurityBuilder) AddFilter(filter SecurityFilter) *SecurityBuilder
AddFilter 添加过滤器
func (*SecurityBuilder) AddFilterAfter ¶
func (b *SecurityBuilder) AddFilterAfter(filter SecurityFilter, after SecurityFilter) *SecurityBuilder
AddFilterAfter 在指定过滤器后添加
func (*SecurityBuilder) AddFilterBefore ¶
func (b *SecurityBuilder) AddFilterBefore(filter SecurityFilter, before SecurityFilter) *SecurityBuilder
AddFilterBefore 在指定过滤器前添加
func (*SecurityBuilder) AuthenticationManager ¶
func (b *SecurityBuilder) AuthenticationManager(manager AuthenticationManager) *SecurityBuilder
AuthenticationManager 设置认证管理器
func (*SecurityBuilder) EnableAnonymous ¶
func (b *SecurityBuilder) EnableAnonymous() *SecurityBuilder
EnableAnonymous 启用匿名访问
func (*SecurityBuilder) EnableCsrf ¶
func (b *SecurityBuilder) EnableCsrf() *SecurityBuilder
EnableCsrf 启用 CSRF 保护
func (*SecurityBuilder) EnableFormLogin ¶
func (b *SecurityBuilder) EnableFormLogin(processingUrl string, defaultSuccessUrl ...string) *SecurityBuilder
EnableFormLogin 启用表单登录
func (*SecurityBuilder) EnableHttpBasic ¶
func (b *SecurityBuilder) EnableHttpBasic() *SecurityBuilder
EnableHttpBasic 启用 HTTP Basic 认证
func (*SecurityBuilder) EnableLogout ¶
func (b *SecurityBuilder) EnableLogout(url string, successHandler ...LogoutSuccessHandler) *SecurityBuilder
EnableLogout 启用登出
func (*SecurityBuilder) PasswordEncoder ¶
func (b *SecurityBuilder) PasswordEncoder(encoder PasswordEncoder) *SecurityBuilder
PasswordEncoder 设置密码编码器
func (*SecurityBuilder) UserDetailsService ¶
func (b *SecurityBuilder) UserDetailsService(service UserDetailsService) *SecurityBuilder
UserDetailsService 设置用户详情服务
type SecurityConfig ¶
type SecurityConfig interface {
// Configure 配置 HTTP 安全。
Configure(http HttpSecurity) error
}
SecurityConfig 安全配置接口。
提供自定义安全配置的入口。
type SecurityContext ¶
type SecurityContext interface {
// Authentication 获取当前认证信息。
Authentication() Authentication
// SetAuthentication 设置认证信息。
SetAuthentication(auth Authentication)
// ClearAuthentication 清除认证信息。
ClearAuthentication()
}
SecurityContext 安全上下文接口。
提供对当前认证信息的访问和管理。 通常与请求生命周期绑定,用于存储和检索认证主体信息。
使用示例:
ctx := security.NewSecurityContext() ctx.SetAuthentication(auth) auth := ctx.Authentication()
type SecurityContextHolderFilter ¶
type SecurityContextHolderFilter struct{}
SecurityContextHolderFilter 安全上下文持有者过滤器。
在过滤器链执行完成后,将最终认证信息保存到请求属性中, 供下游 HTTP 处理器使用。
func NewSecurityContextHolderFilter ¶
func NewSecurityContextHolderFilter() *SecurityContextHolderFilter
func (*SecurityContextHolderFilter) DoFilter ¶
func (f *SecurityContextHolderFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*SecurityContextHolderFilter) Order ¶ added in v0.0.3
func (f *SecurityContextHolderFilter) Order() int
Order 实现 filter.Filter 接口
type SecurityContextLogoutHandler ¶
type SecurityContextLogoutHandler struct{}
SecurityContextLogoutHandler 安全上下文登出处理器
func NewSecurityContextLogoutHandler ¶
func NewSecurityContextLogoutHandler() *SecurityContextLogoutHandler
func (*SecurityContextLogoutHandler) Logout ¶
func (h *SecurityContextLogoutHandler) Logout(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
type SecurityFilterChain ¶
type SecurityFilterChain = filter.SecurityFilterChain
type SecurityFilterChainHandler ¶
type SecurityFilterChainHandler struct {
// contains filtered or unexported fields
}
SecurityFilterChainHandler 安全过滤器链处理器
func NewSecurityFilterChainHandler ¶
func NewSecurityFilterChainHandler(securityFilterChain SecurityFilterChain, nextHandler http.Handler) *SecurityFilterChainHandler
func (*SecurityFilterChainHandler) ServeHTTP ¶
func (h *SecurityFilterChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP 实现http.Handler接口
func (*SecurityFilterChainHandler) SetNextHandler ¶
func (h *SecurityFilterChainHandler) SetNextHandler(handler http.Handler)
SetNextHandler 设置下一个 HTTP 处理器(用于过滤器链接力)。
type SecurityMetadataSource ¶
type SecurityMetadataSource interface {
// GetAttributes 获取安全属性。
GetAttributes(ctx context.Context, request SecurityRequest) ([]string, error)
}
SecurityMetadataSource 安全元数据源接口。
提供访问资源所需的安全属性(如角色要求)。 用于动态访问控制决策。
type SecurityRequest ¶
type SecurityRequest interface {
// GetMethod 获取请求方法。
GetMethod() string
// GetURI 获取请求 URI。
GetURI() string
// GetHeader 获取请求头。
GetHeader(key string) string
// RemoteAddress 获取直连对端的地址,格式为 "host:port"。
RemoteAddress() string
// SetAttribute 设置请求属性。
SetAttribute(key string, value any)
// GetAttribute 获取请求属性。
GetAttribute(key string) (any, bool)
}
SecurityRequest 安全请求接口。
抽象 HTTP 请求,提供安全相关的访问方法。 用于获取请求方法、URI、头部等信息。
type SecurityResponse ¶
type SecurityResponse interface {
// SetStatusCode 设置状态码。
SetStatusCode(code int)
// SetHeader 设置响应头。
SetHeader(key, value string)
// Write 写入响应数据。
Write(data []byte) error
}
SecurityResponse 安全响应接口。
抽象 HTTP 响应,提供安全相关的修改方法。 用于设置状态码、头部和响应体。
type Sha256PasswordEncoder
deprecated
type Sha256PasswordEncoder struct{}
Sha256PasswordEncoder 基于 SHA256 的密码编码器
Deprecated: 此实现不使用 salt,易受彩虹表攻击。 仅适用于兼容性场景,不推荐用于生产环境。 生产环境应使用 BCryptPasswordEncoder 或 Argon2PasswordEncoder。
func NewSha256PasswordEncoder ¶
func NewSha256PasswordEncoder() *Sha256PasswordEncoder
NewSha256PasswordEncoder 创建 SHA256 密码编码器
func (*Sha256PasswordEncoder) Encode ¶
func (e *Sha256PasswordEncoder) Encode(rawPassword string) string
Encode 使用 SHA256 算法编码密码
func (*Sha256PasswordEncoder) Matches ¶
func (e *Sha256PasswordEncoder) Matches(rawPassword, encodedPassword string) bool
Matches 比较编码后的密码
type SimpleLogoutSuccessHandler ¶
type SimpleLogoutSuccessHandler struct {
// contains filtered or unexported fields
}
SimpleLogoutSuccessHandler 简单登出成功处理器
func NewSimpleLogoutSuccessHandler ¶
func NewSimpleLogoutSuccessHandler(targetUrl string) *SimpleLogoutSuccessHandler
func (*SimpleLogoutSuccessHandler) OnLogoutSuccess ¶
func (h *SimpleLogoutSuccessHandler) OnLogoutSuccess(ctx context.Context, request SecurityRequest, response SecurityResponse, authentication Authentication)
type SlidingWindowRateLimiter ¶
type SlidingWindowRateLimiter struct {
// contains filtered or unexported fields
}
SlidingWindowRateLimiter 滑动窗口限流器
func NewSlidingWindowRateLimiter ¶
func NewSlidingWindowRateLimiter(windowSize time.Duration, maxRequests int) *SlidingWindowRateLimiter
func (*SlidingWindowRateLimiter) Allow ¶
func (r *SlidingWindowRateLimiter) Allow(key string) bool
Allow 检查指定 key 的请求是否允许通过(滑动窗口算法)。
func (*SlidingWindowRateLimiter) Cleanup ¶
func (r *SlidingWindowRateLimiter) Cleanup()
Cleanup 清理滑动窗口中过期的请求记录,释放内存。
func (*SlidingWindowRateLimiter) Close ¶ added in v0.0.4
func (r *SlidingWindowRateLimiter) Close()
Close 关闭滑动窗口限流器,停止后台清理协程。
type StandardPasswordEncoder ¶
type StandardPasswordEncoder struct {
// contains filtered or unexported fields
}
StandardPasswordEncoder 标准密码编码器 使用密钥对密码进行SHA256哈希
func NewStandardPasswordEncoder ¶
func NewStandardPasswordEncoder(secret string) *StandardPasswordEncoder
NewStandardPasswordEncoder 创建标准密码编码器 secret: 用于加盐的密钥
func (*StandardPasswordEncoder) Encode ¶
func (e *StandardPasswordEncoder) Encode(rawPassword string) string
Encode 使用密钥对密码进行编码
func (*StandardPasswordEncoder) Matches ¶
func (e *StandardPasswordEncoder) Matches(rawPassword, encodedPassword string) bool
Matches 比较编码后的密码
type StrategyRateLimiterAdapter ¶
type StrategyRateLimiterAdapter struct {
// contains filtered or unexported fields
}
StrategyRateLimiterAdapter 限流器适配器
func NewStrategyRateLimiterAdapter ¶
func NewStrategyRateLimiterAdapter(limiter RateLimiter) *StrategyRateLimiterAdapter
func (*StrategyRateLimiterAdapter) Allow ¶
func (a *StrategyRateLimiterAdapter) Allow(key string) bool
Allow 委托内部限流器检查指定 key 的请求是否允许通过。
type TokenBucket ¶
type TokenBucket struct {
// contains filtered or unexported fields
}
TokenBucket 令牌桶
func NewTokenBucket ¶
func NewTokenBucket(capacity, rate int) *TokenBucket
func (*TokenBucket) IsExpired ¶ added in v0.0.4
func (b *TokenBucket) IsExpired(ttl time.Duration) bool
IsExpired 判断令牌桶是否已超过 ttl 未被访问。
func (*TokenBucket) Take ¶
func (b *TokenBucket) Take() bool
type UnanimousBased ¶
type UnanimousBased struct {
// contains filtered or unexported fields
}
UnanimousBased 一致通过访问决策管理器
func NewUnanimousBased ¶
func NewUnanimousBased(voters ...AccessDecisionVoter) *UnanimousBased
func (*UnanimousBased) AddVoter ¶
func (m *UnanimousBased) AddVoter(voter AccessDecisionVoter)
AddVoter 添加访问决策投票者到决策管理器。
func (*UnanimousBased) Decide ¶
func (m *UnanimousBased) Decide(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) error
Decide 决定是否授予访问权限
func (*UnanimousBased) SetAllowIfAllAbstainDecisions ¶
func (m *UnanimousBased) SetAllowIfAllAbstainDecisions(allow bool)
SetAllowIfAllAbstainDecisions 设置当所有投票者都弃权时是否允许访问。
func (*UnanimousBased) Supports ¶ added in v0.0.3
func (m *UnanimousBased) Supports(attribute string) bool
Supports 是否支持该决策属性
type UserDetails ¶
type UserDetails = authentication.UserDetails
type UserDetailsService ¶
type UserDetailsService = authentication.UserDetailsService
Example ¶
ExampleUserDetailsService 使用示例:用户详情服务 展示如何创建和管理用户
service := NewInMemoryUserDetailsService()
service.CreateUser("john", "password123", []string{"ROLE_USER"})
service.CreateUser("jane", "password456", []string{"ROLE_USER", "ROLE_ADMIN"})
ctx := context.Background()
john, _ := service.LoadUserByUsername(ctx, "john")
fmt.Printf("Username: %s\n", john.Username())
fmt.Printf("Authorities: %v\n", john.Authorities())
fmt.Printf("Total users: %d\n", service.UserCount())
service.DeleteUser("john")
fmt.Printf("Users after delete: %d\n", service.UserCount())
type UsernamePasswordAuthenticationFilter ¶
type UsernamePasswordAuthenticationFilter struct {
// contains filtered or unexported fields
}
UsernamePasswordAuthenticationFilter 用户名密码认证过滤器
func NewUsernamePasswordAuthenticationFilterWithDefaults ¶
func NewUsernamePasswordAuthenticationFilterWithDefaults( loginProcessingURL, defaultSuccessURL, failureURL string, authManager AuthenticationManager, logger log.Logger, ) *UsernamePasswordAuthenticationFilter
func (*UsernamePasswordAuthenticationFilter) DoFilter ¶
func (f *UsernamePasswordAuthenticationFilter) DoFilter(ctx interface{}, request interface{}, response interface{}, chain filter.FilterChain) error
DoFilter 实现 filter.Filter 接口
func (*UsernamePasswordAuthenticationFilter) Order ¶ added in v0.0.3
func (f *UsernamePasswordAuthenticationFilter) Order() int
Order 实现 filter.Filter 接口
type UsernamePasswordAuthenticationToken ¶
type UsernamePasswordAuthenticationToken struct {
// contains filtered or unexported fields
}
UsernamePasswordAuthenticationToken 用户名密码认证令牌
func NewAuthenticatedUsernamePasswordAuthenticationToken ¶
func NewAuthenticatedUsernamePasswordAuthenticationToken(principal any, authorities []string) *UsernamePasswordAuthenticationToken
NewAuthenticatedUsernamePasswordAuthenticationToken 创建已认证的用户名密码令牌
func NewUsernamePasswordAuthenticationToken ¶
func NewUsernamePasswordAuthenticationToken(principal, credentials any) *UsernamePasswordAuthenticationToken
NewUsernamePasswordAuthenticationToken 创建未认证的用户名密码令牌
func (*UsernamePasswordAuthenticationToken) Authenticated ¶
func (t *UsernamePasswordAuthenticationToken) Authenticated() bool
Authenticated 返回认证令牌是否已通过验证。
func (*UsernamePasswordAuthenticationToken) Authorities ¶
func (t *UsernamePasswordAuthenticationToken) Authorities() []string
Authorities 返回认证令牌的授权列表(返回副本以保证安全)。
func (*UsernamePasswordAuthenticationToken) Credentials ¶
func (t *UsernamePasswordAuthenticationToken) Credentials() any
Credentials 返回认证凭证(如密码)。
func (*UsernamePasswordAuthenticationToken) Name ¶
func (t *UsernamePasswordAuthenticationToken) Name() string
Name 返回认证主体名称
func (*UsernamePasswordAuthenticationToken) Principal ¶
func (t *UsernamePasswordAuthenticationToken) Principal() any
Principal 返回认证主体的身份信息(如用户名)。
func (*UsernamePasswordAuthenticationToken) SetAuthenticated ¶
func (t *UsernamePasswordAuthenticationToken) SetAuthenticated(authenticated bool)
SetAuthenticated 设置认证状态 SetAuthenticated 设置认证令牌的认证状态。
func (*UsernamePasswordAuthenticationToken) SetAuthorities ¶
func (t *UsernamePasswordAuthenticationToken) SetAuthorities(authorities []string)
SetAuthorities 设置授权列表 SetAuthorities 设置认证令牌的授权列表。
type VirtualFilterChain ¶
type VirtualFilterChain struct {
// contains filtered or unexported fields
}
VirtualFilterChain 虚拟过滤器链
func (*VirtualFilterChain) DoFilter ¶
func (c *VirtualFilterChain) DoFilter(ctx context.Context, request SecurityRequest, response SecurityResponse) error
DoFilter 执行下一个过滤器
type WebExpressionVoter ¶
type WebExpressionVoter struct{}
WebExpressionVoter Web表达式投票者
func NewWebExpressionVoter ¶
func NewWebExpressionVoter() *WebExpressionVoter
func (*WebExpressionVoter) Supports ¶ added in v0.0.3
func (v *WebExpressionVoter) Supports(attribute string) bool
Supports 是否支持该属性
func (*WebExpressionVoter) Vote ¶
func (v *WebExpressionVoter) Vote(ctx context.Context, authentication authorization.Authentication, resource string, attributes []string) int
Vote 投票决定访问权限
type WebSecurity ¶
type WebSecurity struct{}
WebSecurity Web安全配置入口
func (*WebSecurity) Build ¶
func (w *WebSecurity) Build() (SecurityFilterChain, error)
Build 构建安全过滤器链(WebSecurity 的 Build 方法仅用作占位)。
func (*WebSecurity) HttpSecurity ¶
func (w *WebSecurity) HttpSecurity() *httpSecurity
HttpSecurity 创建一个新的 HttpSecurity 构建器实例。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authentication 提供认证功能支持,用于 enhance 框架。
|
Package authentication 提供认证功能支持,用于 enhance 框架。 |
|
Package authorization 提供授权功能支持,用于 enhance 框架。
|
Package authorization 提供授权功能支持,用于 enhance 框架。 |
|
Package filter 提供安全过滤器链抽象,用于 enhance 框架。
|
Package filter 提供安全过滤器链抽象,用于 enhance 框架。 |