-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
196 lines (165 loc) · 5.06 KB
/
auth.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package apiserver
import (
"context"
"encoding/base64"
"net/http"
"strings"
"time"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
v1 "github.com/rose839/IAM/api/apiserver/v1"
metav1 "github.com/rose839/IAM/api/meta/v1"
"github.com/rose839/IAM/internal/apiserver/store"
"github.com/rose839/IAM/internal/pkg/middleware"
"github.com/rose839/IAM/internal/pkg/middleware/auth"
"github.com/spf13/viper"
)
const (
// APIServerAudience defines the value of jwt audience field.
APIServerAudience = "iam.api.rose839.com"
// APIServerIssuer defines the value of jwt issuer field.
APIServerIssuer = "iam-apiserver"
)
type loginInfo struct {
Username string `form:"username" json:"username" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func newBasicAuth() middleware.AuthStrategy {
return auth.NewBasicStrategy(func(username string, password string) bool {
// fetch user from database
user, err := store.Client().Users().Get(context.TODO(), username, metav1.GetOptions{})
if err != nil {
return false
}
// Compare the login password with the user password.
if err := user.Compare(password); err != nil {
return false
}
return true
})
}
func newJWTAuth() middleware.AuthStrategy {
ginjwt, _ := jwt.New(&jwt.GinJWTMiddleware{
Realm: viper.GetString("jwt.Realm"),
SigningAlgorithm: "HS256",
Key: []byte(viper.GetString("jwt.key")),
Timeout: viper.GetDuration("jwt.timeout"),
MaxRefresh: viper.GetDuration("jwt.max-refresh"),
Authenticator: authenticator(),
LoginResponse: loginResponse(),
LogoutResponse: func(c *gin.Context, code int) {
c.JSON(http.StatusOK, nil)
},
RefreshResponse: refreshResponse(),
PayloadFunc: payloadFunc(),
IdentityKey: middleware.UsernameKey,
IdentityHandler: func(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
return claims[jwt.IdentityKey]
},
Authorizator: authorizator(),
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"message": message,
})
},
TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenHeadName: "Bearer",
SendCookie: true,
TimeFunc: time.Now,
})
return auth.NewJWTStrategy(*ginjwt)
}
func newAutoAuth() middleware.AuthStrategy {
return auth.NewAutoStrategy(newBasicAuth().(auth.BasicStrategy), newJWTAuth().(auth.JWTStrategy))
}
// parse header to get username and password, used for basic auth.
func parseWithHeader(c *gin.Context) (loginInfo, error) {
auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
return loginInfo{}, jwt.ErrFailedAuthentication
}
payload, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil {
return loginInfo{}, jwt.ErrFailedAuthentication
}
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 {
return loginInfo{}, jwt.ErrFailedAuthentication
}
return loginInfo{
Username: pair[0],
Password: pair[1],
}, nil
}
// parse body to get username and password, used for basic auth.
func parseWithBody(c *gin.Context) (loginInfo, error) {
var login loginInfo
if err := c.ShouldBindJSON(&login); err != nil {
return loginInfo{}, jwt.ErrFailedAuthentication
}
return login, nil
}
// basic auth func.
func authenticator() func(c *gin.Context) (interface{}, error) {
return func(c *gin.Context) (interface{}, error) {
var login loginInfo
var err error
// support header and body basic auth.
if c.Request.Header.Get("Authorization") != "" {
login, err = parseWithHeader(c)
} else {
login, err = parseWithBody(c)
}
if err != nil {
return "", jwt.ErrFailedAuthentication
}
// Get the user information by username.
user, err := store.Client().Users().Get(c, login.Username, metav1.GetOptions{})
if err != nil {
return "", jwt.ErrFailedAuthentication
}
// Compare the login password with the user password.
if err := user.Compare(login.Password); err != nil {
return "", jwt.ErrFailedAuthentication
}
return user, nil
}
}
func loginResponse() func(c *gin.Context, code int, token string, expire time.Time) {
return func(c *gin.Context, code int, token string, expire time.Time) {
c.JSON(http.StatusOK, gin.H{
"token": token,
"expire": expire.Format(time.RFC3339),
})
}
}
func refreshResponse() func(c *gin.Context, code int, token string, expire time.Time) {
return func(c *gin.Context, code int, token string, expire time.Time) {
c.JSON(http.StatusOK, gin.H{
"token": token,
"expire": expire.Format(time.RFC3339),
})
}
}
func payloadFunc() func(data interface{}) jwt.MapClaims {
return func(data interface{}) jwt.MapClaims {
claims := jwt.MapClaims{
"iss": APIServerIssuer,
"aud": APIServerAudience,
}
if u, ok := data.(*v1.User); ok {
claims[jwt.IdentityKey] = u.Name
claims["sub"] = u.Name
}
return claims
}
}
func authorizator() func(data interface{}, c *gin.Context) bool {
return func(data interface{}, c *gin.Context) bool {
if _, ok := data.(string); ok {
return true
}
return false
}
}