tokenauth

package module
v0.0.0-...-84e0530 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2015 License: Apache-2.0 Imports: 18 Imported by: 5

README

tokenauth

tokenauth 是一个 token 维护验证存储包,支持单点和多点模式,默认使用 boltdbf 存储 token 数据。

安装

go get github.com/ysqi/tokenauth

也可以通过-u参数来更新tokenauth 和所依赖的第三方包

go get -u github.com/ysqi/tokenauth

功能

  • 支持自定义存储
  • 默认使用boltdbf存储token到本地
  • 随机生成客户令牌
  • 自定义算法生成 Token
  • 支持对一个客户维护N个Token
  • 支持对一个客户仅维护一个 Token
  • 支持Token有效性验证

使用场景

为第三方客户端颁发Token

作为使用平台,第三方可注册使用平台服务,当客户端登录成功后单一客户端拉取一个全新Token,后续客户端可直接携带 Token访问平台资源,而不需要提供账号和密码信息,同时可在Token到期后请求拉取新 Token。

单点登录

用户在第一次成功登录后,可给用户拉取一个全新Token,同时该用户相关的旧Token立即失效。用户可以使用该 Token 访问其他子系统,如 App 登录后,可 URL 携带 Token 访问 Web 站点资源。

简单使用

import (
	"fmt"
	"github.com/ysqi/tokenauth"
)
func main() {

	if err := tokenauth.UseDeaultStore(); err != nil {
		panic(err)
	}
	defer tokenauth.Store.Close()

	// Ready.
	d := &tokenauth.DefaultProvider{}
	globalClient := tokenauth.NewAudienceNotStore("globalClient", d.GenerateSecretString)

	//New token
	token, err := tokenauth.NewSingleToken("singleID", globalClient, d.GenerateTokenString)
	if err != nil {
		fmt.Println("generate token fail,", err.Error())
		return
	}
	 Check token
	if checkToken, err := tokenauth.ValidateToken(token.Value); err != nil {
		fmt.Println("token check did not pass,", err.Error())
	} else {
		fmt.Println("token check pass,token Expiration date:", checkToken.DeadLine)
	}

}

1.程序初始化时,需手动选择Store方案

  • 选择默认方案:
tokenauth.UseDeaultStore();
  • 选择自定义Store
if store, err := tokenauth.NewStore(newStoreName, storeConf); err != nil {
	panic(err)
}else if err = tokenauth.ChangeTokenStore(store); err != nil {
	panic(err)
}

2.定义生成密钥 Secret 和 Token 算法

  • 选择默认算法:
d := &tokenauth.DefaultProvider{}
secretFunc := d.GenerateSecretString
tokenFunc := d.GenerateTokenString
  • 选择自定义算法
secretFunc := func(clientID string) (secretString string) { return "myself secret for all client" }
tokenFunc := func(audience *Audience) string { return "same token string" }

3.使用算法在 Store 中创建存储一个听众(相当于用户)

client := tokenauth.NewAudienceNotStore("client name", secretFunc)

4.使用算法给用户颁发一个或多个Token

token, err := tokenauth.NewToken(client, tokenFunc)
if err != nil {
	fmt.Println("generate token fail,", err.Error())
}

// more ...
t2 ,err  := tokenauth.NewToken(client, tokenFunc)

每个Token 都要自己的生命周期,Store自动定期清除过期Token,默认有效时常为:tokenauth.TokenPeriod

5.验证 Token String 的有效性

if checkToken, err := tokenauth.ValidateToken(tokenString); err != nil {
	fmt.Println("token check did not pass,", err.Error())
} else {
	fmt.Println("token check pass,token Expiration date:", checkToken.DeadLine)
}

6.当然可以主动删除 Token

err:=tokenauth.Store.DeleteToken(tokenString)

Documentation

Overview

Package Token generation and storage management . Simple Usage.

import (
	"fmt"
	"github.com/ysqi/tokenauth"
)
func main() {

	if err := tokenauth.UseDeaultStore(); err != nil {
		panic(err)
	}
	defer tokenauth.Store.Close()

	// Ready.
	d := &tokenauth.DefaultProvider{}
	globalClient := tokenauth.NewAudienceNotStore("globalClient", d.GenerateSecretString)

	// New token
	token, err := tokenauth.NewSingleToken("singleID", globalClient, d.GenerateTokenString)
	if err != nil {
		fmt.Println("generate token fail,", err.Error())
		return
	}
	// Check token
	if checkToken, err := tokenauth.ValidateToken(token.Value); err != nil {
		fmt.Println("token check did not pass,", err.Error())
	} else {
		fmt.Println("token check pass,token Expiration date:", checkToken.DeadLine)
	}

}

Advanced Usage:

secretFunc := func(clientID string) (secretString string) {
	return "myself secret for all client"
}
tokenFunc := func(audience *Audience) string {
	return "same token string"
}
globalClient := tokenauth.NewAudienceNotStore("globalClient", secretFunc)
// New token
t1, err := tokenauth.NewToken(globalClient, tokenFunc)
t2, err := tokenauth.NewToken(globalClient, tokenFunc)

Index

Constants

View Source
const (
	// default secret length.
	SecretLength = 32
)

Variables

View Source
var (
	ERR_InvalidateToken = ValidationError{Code: "40001", Msg: "Invalid token"}
	ERR_TokenEmpty      = ValidationError{Code: "41001", Msg: "Token is empty"}
	ERR_TokenExpired    = ValidationError{Code: "42001", Msg: "Token is expired"}
)
View Source
var TokenPeriod uint64 = 7200 //2hour

Token effective time,unti: seconds. Defult is 2 Hour.

Functions

func ChangeTokenStore

func ChangeTokenStore(newStore TokenStore) error

Change token store and close old store. New token and New Audience whill be saved to new store,after use new store.

func GenerateRandomString

func GenerateRandomString(size int, encodeToBase32 bool) string

Returns s random string

func RegStore

func RegStore(name string, adapter TokenStore)

Resister one store provider. If name is empty,will panic. If same name has registerd ,will panic.

func UseDeaultStore

func UseDeaultStore() error

Use default store. Default use bolt db file, "./data/tokendb.bolt" file open or create

Types

type Audience

type Audience struct {
	Name        string
	ID          string // Unique key for audience
	Secret      string //audience secret string,can update.
	TokenPeriod uint64 //token period ,unit: seconds.
}

Audience Info, token rely on audience. Contains secret string , tokenPeriod for generatating token string.

func NewAudience

func NewAudience(name string, secretFunc GenerateSecretString) (*Audience, error)

New audience and this audience will be saved to store.

func NewAudienceNotStore

func NewAudienceNotStore(name string, secretFunc GenerateSecretString) *Audience

Returns a new audience info,not save to store.

type BoltDBFileStore

type BoltDBFileStore struct {
	Alias string
	// contains filtered or unexported fields
}

Store implement by boltdb,see:https://github.com/boltdb/bolt

func NewBoltDBFileStore

func NewBoltDBFileStore() *BoltDBFileStore

new Bolt DB file store instance.

func (*BoltDBFileStore) Close

func (store *BoltDBFileStore) Close() error

Close bolt db

func (*BoltDBFileStore) DBPath

func (store *BoltDBFileStore) DBPath() string

func (*BoltDBFileStore) DeleteAudience

func (store *BoltDBFileStore) DeleteAudience(audienceID string) error

Delete audience and all tokens of audience.

func (*BoltDBFileStore) DeleteExpired

func (store *BoltDBFileStore) DeleteExpired()

Delete token if token expired

func (*BoltDBFileStore) DeleteToken

func (store *BoltDBFileStore) DeleteToken(tokenString string) error

Delete token Returns error if delete token fail.

func (*BoltDBFileStore) GetAudience

func (store *BoltDBFileStore) GetAudience(audienceID string) (audience *Audience, err error)

Get audience info or returns error.

func (*BoltDBFileStore) GetToken

func (store *BoltDBFileStore) GetToken(tokenString string) (token *Token, err error)

Get token info if find in store,or return error

func (*BoltDBFileStore) Open

func (store *BoltDBFileStore) Open(config string) error

Init and Open BoltDBF. config is json string. e.g:

{"path":"./data/tokenbolt.db"}

func (*BoltDBFileStore) SaveAudience

func (store *BoltDBFileStore) SaveAudience(audience *Audience) error

Save audience into store. Returns error if error occured during execution.

func (*BoltDBFileStore) SaveToken

func (store *BoltDBFileStore) SaveToken(token *Token) error

Save token to store. return error when save fail. Save token json to store and save the relation of token with client if not single model. The first , token must not empty and effectiveness. Does not consider concurrency.

type DefaultProvider

type DefaultProvider struct {
	Name string
}

func (*DefaultProvider) GenerateSecretString

func (d *DefaultProvider) GenerateSecretString(clientID string) (secretString string)

func (*DefaultProvider) GenerateTokenString

func (d *DefaultProvider) GenerateTokenString(audience *Audience) string

type GenerateSecretString

type GenerateSecretString func(clientID string) (secretString string) //returns new secret string.

Create Secret provider interface

type GenerateTokenString

type GenerateTokenString func(audience *Audience) string //returns new token string

Create token string provider interface

type ObjectId

type ObjectId string

ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes long. clone from https://github.com/go-mgo/mgo/blob/v2-unstable/bson/bson.go. http://www.mongodb.org/display/DOCS/Object+IDs.

func NewObjectId

func NewObjectId() ObjectId

NewObjectId returns a new unique ObjectId.

func (ObjectId) Counter

func (id ObjectId) Counter() int32

Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) Hex

func (id ObjectId) Hex() string

Hex returns a hex representation of the ObjectId.

func (ObjectId) Machine

func (id ObjectId) Machine() []byte

Machine returns the 3-byte machine id part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) Pid

func (id ObjectId) Pid() uint16

Pid returns the process id part of the id. It's a runtime error to call this method with an invalid id.

func (ObjectId) Time

func (id ObjectId) Time() time.Time

Time returns the timestamp part of the id. It's a runtime error to call this method with an invalid id.

type Token

type Token struct {
	ClientID string // Audience.ID
	SingleID string // Single Token ID
	Value    string // Token string
	DeadLine int64  // Token Expiration date, time unix.
}

Token Info

func NewSingleToken

func NewSingleToken(singleID string, a *Audience, tokenFunc GenerateTokenString) (*Token, error)

New Sign Token and this new token will be saved to store.

func NewToken

func NewToken(a *Audience, tokenFunc GenerateTokenString) (*Token, error)

New Token and this new token will be saved to store.

func ValidateToken

func ValidateToken(tokenString string) (*Token, error)

Returns Exist tokenstring or error. If token is exist but expired, then delete token and return TokenExpired error.

func (*Token) Expired

func (t *Token) Expired() bool

Returns this token is expried. Note: never exprires if token's deadLine =0

func (*Token) IsSingle

func (t *Token) IsSingle() bool

Returns true if token clientID is empty and signleID is not empty.

type TokenStore

type TokenStore interface {

	// Init store
	// Returns error if init fail.
	Open(config string) error

	// Close store
	Close() error

	// Save audience into store.
	// Returns error if error occured during execution.
	SaveAudience(audience *Audience) error

	// Delete audience and  all tokens of audience.
	DeleteAudience(clientID string) error

	// Get audience info or returns error.
	GetAudience(clientID string) (*Audience, error)

	// Save token to token.
	// Returns error if save token fail.
	SaveToken(token *Token) error

	// Delete token info from store.
	// Returns error if error occured during execution
	DeleteToken(tokenString string) error

	// Get token info from store.
	// Returns nil if not found token.
	// Returns error if get token fail.
	GetToken(tokenString string) (*Token, error)

	DeleteExpired()
}

Token store interface.

var Store TokenStore

Global Token Store . Default use

func NewStore

func NewStore(adapterName, config string) (TokenStore, error)

New regiesterd store

type ValidationError

type ValidationError struct {
	Code string `json:"errcode"`
	Msg  string `json:"errmsg"`
}

Customer error.

func (ValidationError) Error

func (v ValidationError) Error() string

Jump to

Keyboard shortcuts

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