-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
112 lines (97 loc) · 2.87 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"fmt"
"net/http"
"time"
"github.com/go-redis/redis/v8"
"github.com/kataras/iris/v12"
"github.com/snowlyg/multi"
multi_iris "github.com/snowlyg/multi/iris"
)
// init 初始化认证驱动
// 驱动类型: 可选 redis ,local,jwt
func init() {
options := &redis.UniversalOptions{
Addrs: []string{"127.0.0.1:6379"},
Password: "",
PoolSize: 10,
IdleTimeout: 300 * time.Second,
// Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
// conn, err := net.Dial(network, addr)
// if err == nil {
// go func() {
// time.Sleep(5 * time.Second)
// conn.Close()
// }()
// }
// return conn, err
// },
}
err := multi.InitDriver(&multi.Config{
DriverType: "redis",
TokenMaxCount: 10,
UniversalClient: redis.NewUniversalClient(options)})
if err != nil {
panic(fmt.Sprintf("auth is not init get err %v\n", err))
}
}
func auth() iris.Handler {
verifier := multi_iris.NewVerifier()
verifier.Extractors = []multi_iris.TokenExtractor{multi_iris.FromHeader} // extract token only from Authorization: Bearer $token
return verifier.Verify()
}
func main() {
app := iris.New()
app.Get("/", generateToken())
protectedAPI := app.Party("/protected")
// Register the verify middleware to allow access only to authorized clients.
protectedAPI.Use(auth())
// ^ or UseRouter(verifyMiddleware) to disallow unauthorized http error handlers too.
protectedAPI.Get("/", protected)
// Invalidate the token through server-side, even if it's not expired yet.
protectedAPI.Get("/logout", logout)
// http://localhost:8080
// http://localhost:8080/protected (or Authorization: Bearer $token)
// http://localhost:8080/protected/logout
// http://localhost:8080/protected (401)
app.Listen(":8080")
}
func generateToken() iris.Handler {
return func(ctx iris.Context) {
claims := &multi.MultiClaims{
Id: "1",
Username: "your name",
AuthorityId: "your authority id",
TenancyId: 1,
TenancyName: "your tenancy name",
AuthorityType: multi.AdminAuthority,
LoginType: multi.LoginTypeWeb,
AuthType: multi.AuthPwd,
CreationDate: time.Now().Local().Unix(),
ExpiresAt: time.Now().Local().Add(multi.RedisSessionTimeoutWeb).Unix(),
}
token, _, err := multi.AuthDriver.GenerateToken(claims)
if err != nil {
ctx.StopWithStatus(http.StatusInternalServerError)
return
}
ctx.WriteString(token)
}
}
func protected(ctx iris.Context) {
claims := multi_iris.Get(ctx)
ctx.Writef("claims=%+v\n", claims)
}
func logout(ctx iris.Context) {
token := multi_iris.GetVerifiedToken(ctx)
if token == nil {
ctx.WriteString("授权凭证为空")
return
}
err := multi.AuthDriver.DelUserTokenCache(string(token))
if err != nil {
ctx.WriteString(err.Error())
return
}
ctx.Writef("token invalidated, a new token is required to access the protected API")
}