token

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 13 Imported by: 0

README

令牌管理

  • 颁发访问令牌,Login
  • 撤销访问令牌,令牌失效 Logout
  • 校验访问令牌,检查令牌的合法性,是否伪造

详细设计

字段: 是根据业务需求来的,基本上是通过产品经理来的

令牌:

  • 过期时间
  • 颁发时间
  • 被颁发的人
  • ...
  1. 业务功能: 令牌的刷新
    • 问题: 无刷新功能,令牌到期了,自动退出了
    • 解决1: 过期时间设置长一点,长时间不登录,又有安全问题
    • 解决2: 令牌过期之后,允许用户刷新(需要使用刷新 Token 来刷新,刷新 Token 也需要过期时间,这个时间取决于你的会话长度),有了刷新 token用户不会出现使用中断的情况,并且长时间未使用,也会退出

Documentation

Index

Constants

View Source
const (
	AccessTokenHeaderName         = "Authorization"
	AccessTokenCookieName         = "access_token"
	AccessTokenResponseHeaderName = "X-OAUTH-TOKEN"
	RefreshTokenHeaderName        = "X-REFRESH-TOKEN"
)
View Source
const (
	IssuerLDAP         = "ldap"
	IssuerFEISHU       = "feishu"
	IssuerPassword     = "password"
	IssuerPrivateToken = "private_token"
)

颁发器的类型

View Source
const (
	AppName = "token"
)

Variables

View Source
var (
	CookieNotFound = exception.NewUnauthorized("cookie %s not found", AccessTokenCookieName)
)
View Source
var (
	CtxTokenKey = tokenContextKey{}
)

Functions

func GetAccessTokenFromHTTP

func GetAccessTokenFromHTTP(r *http.Request) string

GetAccessTokenFromHTTP 从 http 请求头中获取 token 信息

func GetIssueParameterValue

func GetIssueParameterValue[T any](p IssueParameter, key string) T

func GetRefreshTokenFromHTTP

func GetRefreshTokenFromHTTP(r *http.Request) string

GetRefreshTokenFromHTTP 从 http 请求头中获取刷新 token

func MakeBearer

func MakeBearer(length int) string

MakeBearer 产生随机字符串

func RegistryIssuer

func RegistryIssuer(name string, p Issuer)

RegistryIssuer 注册颁发器

Types

type DescribeBy

type DescribeBy int
const (
	DescribeByAccessToken DescribeBy = iota
)

type DescribeTokenRequest

type DescribeTokenRequest struct {
	DescribeBy    DescribeBy `json:"describe_by"`
	DescribeValue string     `json:"describe_value"`
}

func NewDescribeTokenRequest

func NewDescribeTokenRequest(accessToken string) *DescribeTokenRequest

type IssueParameter

type IssueParameter map[string]any

func NewIssueParameter

func NewIssueParameter() IssueParameter

func (IssueParameter) AccessToken

func (p IssueParameter) AccessToken() string

func (IssueParameter) ExpireTTL

func (p IssueParameter) ExpireTTL() time.Duration

func (IssueParameter) Password

func (p IssueParameter) Password() string

func (IssueParameter) SetAccessToken

func (p IssueParameter) SetAccessToken(v string) IssueParameter

func (IssueParameter) SetExpireTTL

func (p IssueParameter) SetExpireTTL(v int64) IssueParameter

func (IssueParameter) SetPassword

func (p IssueParameter) SetPassword(v string) IssueParameter

func (IssueParameter) SetUsername

func (p IssueParameter) SetUsername(v string) IssueParameter

func (IssueParameter) Username

func (p IssueParameter) Username() string

type IssueTokenRequest

type IssueTokenRequest struct {
	// Source 端类型
	Source SOURCE `json:"source"`
	// Issuer 认证方式
	Issuer string `json:"issuer"`
	// Parameter 参数
	Parameter IssueParameter `json:"parameter"`
}

IssueTokenRequest 用户的身份的凭证,用于换取token

func NewIssueTokenRequest

func NewIssueTokenRequest() *IssueTokenRequest

func (*IssueTokenRequest) IssueByPassword

func (i *IssueTokenRequest) IssueByPassword(username, password string)

type Issuer

type Issuer interface {
	// IssueToken 颁发 token 的接口
	IssueToken(context.Context, IssueParameter) (*Token, error)
}

Issuer 颁发器必须实现的接口

func GetIssuer

func GetIssuer(name string) Issuer

type LockType

type LockType int
const (
	// LockTypeRevoke 用户退出登录
	LockTypeRevoke LockType = iota
	// LockTypeTokenExpired 刷新 token 过期,会话中断
	LockTypeTokenExpired
	// LockTypeOtherPlaceLoggedIn 异地登录
	LockTypeOtherPlaceLoggedIn
	// LockTypeOtherIpLoggedIn 异常 ip 登录
	LockTypeOtherIpLoggedIn
)

type QueryTokenRequest

type QueryTokenRequest struct {
	*request.PageRequest
	Active  *bool    `json:"active"`   // 当前可用的没过期的 token
	Source  *SOURCE  `json:"source"`   // 用户来源
	UserIds []uint64 `json:"user_ids"` // user_ids
}

func NewQueryTokenRequest

func NewQueryTokenRequest() *QueryTokenRequest

func (*QueryTokenRequest) AddUserId

func (r *QueryTokenRequest) AddUserId(userIds ...uint64) *QueryTokenRequest

func (*QueryTokenRequest) SetActive

func (r *QueryTokenRequest) SetActive(v bool) *QueryTokenRequest

func (*QueryTokenRequest) SetSource

func (r *QueryTokenRequest) SetSource(v SOURCE) *QueryTokenRequest

type RevokeTokenRequest

type RevokeTokenRequest struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
}

func NewRevokeTokenRequest

func NewRevokeTokenRequest(at string, rt string) *RevokeTokenRequest

type SOURCE

type SOURCE int

SOURCE 来源定义

const (
	// SourceUnknown 未知
	SourceUnknown SOURCE = iota
	// SourceWeb web
	SourceWeb
	// SourceIos ios
	SourceIos
	// SourceAndroid android
	SourceAndroid
	// SourcePc PC
	SourcePc
	// SourceApi api 调用
	SourceApi SOURCE = 10
)

type Service

type Service interface {
	// IssueToken 颁发令牌: Login
	IssueToken(context.Context, *IssueTokenRequest) (*Token, error)
	// RevokeToken 撤销令牌: Logout
	RevokeToken(context.Context, *RevokeTokenRequest) (*Token, error)
	// ValidateToken 验证令牌: 检查令牌的合法性,是否伪造
	ValidateToken(context.Context, *ValidateTokenRequest) (*Token, error)
	// QueryToken 查询已经颁发出去的 token
	QueryToken(context.Context, *QueryTokenRequest) (*types.Set[*Token], error)
	DescribeToken(context.Context, *DescribeTokenRequest) (*Token, error)
}

func GetService

func GetService() Service

type Status

type Status struct {
	// 冻结时间
	LockAt *time.Time `json:"lock_at" bson:"lock_at" gorm:"column:lock_at;type:timestamp;index" description:"冻结时间"`
	// 冻结类型
	LockType LockType `` /* 203-byte string literal not displayed */
	// 冻结原因
	LockReason string `json:"lock_reason" bson:"lock_reason" gorm:"column:lock_reason;type:text" description:"冻结原因"`
}

func NewStatus

func NewStatus() *Status

func (*Status) SetLockAt

func (s *Status) SetLockAt(v time.Time)

func (*Status) ToMap

func (s *Status) ToMap() map[string]any

type Token

type Token struct {
	Id uint64 `json:"id" gorm:"column:id;type:uint;primaryKey"`
	// 用户来源
	Source SOURCE `json:"source" gorm:"column:source;type:tinyint(1);index" description:"用户来源"`
	// 颁发器, 办法方式(user/pass )
	Issuer string `json:"issuer" gorm:"column:issuer;type:varchar(100);index" description:"颁发器"`
	// 该Token属于哪个用户
	UserId uint64 `json:"user_id" gorm:"column:user_id;index" description:"持有该Token的用户Id"`
	// 用户名
	UserName string `json:"user_name" gorm:"column:user_name;type:varchar(100);not null;index" description:"持有该Token的用户名称"`
	// 是不是管理员
	IsAdmin bool `json:"is_admin" gorm:"column:is_admin;type:tinyint(1)" description:"是不是管理员"`

	// 令牌生效范围
	policy.ResourceScope

	// 令牌生效空间Id
	//NamespaceId uint64 `json:"namespace_id" gorm:"column:namespace_id;type:uint;index" description:"令牌所属空间Id"`
	// 令牌生效空间名称
	NamespaceName string `json:"namespace_name" gorm:"column:namespace_name;type:varchar(100);index" description:"令牌所属空间"`
	// 访问范围定义, 鉴权完成后补充
	Scope map[string]string `json:"scope" gorm:"column:scope;type:varchar(100);serializer:json" description:"令牌访问范围定义"`
	// 颁发给用户的访问令牌(用户需要携带Token来访问接口)
	AccessToken string `json:"access_token" gorm:"column:access_token;type:varchar(100);not null;uniqueIndex" description:"访问令牌"`
	// 访问令牌过期时间
	AccessTokenExpiredAt *time.Time `` /* 131-byte string literal not displayed */
	// 刷新Token
	RefreshToken string `json:"refresh_token" gorm:"column:refresh_token;type:varchar(100);not null;uniqueIndex" description:"刷新令牌"`
	// 刷新Token过期时间
	RefreshTokenExpiredAt *time.Time `` /* 133-byte string literal not displayed */
	// 创建时间
	IssueAt time.Time `` /* 127-byte string literal not displayed */
	// 更新时间
	RefreshAt *time.Time `json:"refresh_at" gorm:"column:refresh_at;type:timestamp" description:"令牌刷新时间"`
	// 令牌状态
	Status *Status `json:"status" gorm:"embedded" modelDescription:"令牌状态"`
	// 其他扩展信息
	Extras map[string]string `json:"extras" gorm:"column:extras;serializer:json;type:json" description:"其他扩展信息"`
}

func GetTokenFromCtx

func GetTokenFromCtx(ctx context.Context) *Token

GetTokenFromCtx 从 context 上下文中获取 token 信息

func NewToken

func NewToken() *Token

func (*Token) AccessTokenExpiredTTL

func (t *Token) AccessTokenExpiredTTL() int

func (*Token) CheckRefreshToken

func (t *Token) CheckRefreshToken(refreshToken string) error

func (*Token) IsAccessTokenExpired

func (t *Token) IsAccessTokenExpired() error

IsAccessTokenExpired 判断访问令牌是否过期,没设置代表永不过期

func (*Token) IsRefreshTokenExpired

func (t *Token) IsRefreshTokenExpired() error

IsRefreshTokenExpired 判断刷新 token 是否过期

func (*Token) Lock

func (t *Token) Lock(l LockType, reason string)

func (*Token) SetAccessTokenExpiredAt

func (t *Token) SetAccessTokenExpiredAt(v time.Time)

func (*Token) SetExpiredAtByDuration

func (t *Token) SetExpiredAtByDuration(duration time.Duration, refreshMulti uint)

func (*Token) SetIssuer

func (t *Token) SetIssuer(issuer string) *Token

func (*Token) SetRefreshAt

func (t *Token) SetRefreshAt(v time.Time)

func (*Token) SetRefreshTokenExpiredAt

func (t *Token) SetRefreshTokenExpiredAt(v time.Time)

func (*Token) SetSource

func (t *Token) SetSource(source SOURCE) *Token

func (*Token) String

func (t *Token) String() string

func (*Token) TableName

func (t *Token) TableName() string

TableName 表名

func (*Token) UserIdString

func (t *Token) UserIdString() string

type ValidateTokenRequest

type ValidateTokenRequest struct {
	AccessToken string `json:"access_token"`
}

func NewValidateTokenRequest

func NewValidateTokenRequest(accessToken string) *ValidateTokenRequest

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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