login record CRD (#2565)
* Signed-off-by: hongming <talonwan@yunify.com> support ldap identity provider Signed-off-by: hongming <talonwan@yunify.com> * add login record Signed-off-by: Jeff <zw0948@gmail.com> Co-authored-by: hongming <talonwan@yunify.com>
This commit is contained in:
@@ -16,16 +16,24 @@ limitations under the License.
|
||||
|
||||
package token
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"k8s.io/apiserver/pkg/authentication/user"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AccessToken TokenType = "access_token"
|
||||
RefreshToken TokenType = "refresh_token"
|
||||
StaticToken TokenType = "static_token"
|
||||
)
|
||||
|
||||
type TokenType string
|
||||
|
||||
// Issuer issues token to user, tokens are required to perform mutating requests to resources
|
||||
type Issuer interface {
|
||||
// IssueTo issues a token a User, return error if issuing process failed
|
||||
IssueTo(user User, expiresIn time.Duration) (string, error)
|
||||
IssueTo(user user.Info, tokenType TokenType, expiresIn time.Duration) (string, error)
|
||||
|
||||
// Verify verifies a token, and return a User if it's a valid token, otherwise return error
|
||||
Verify(string) (User, error)
|
||||
|
||||
// Revoke a token,
|
||||
Revoke(token string) error
|
||||
// Verify verifies a token, and return a user info if it's a valid token, otherwise return error
|
||||
Verify(string) (user.Info, TokenType, error)
|
||||
}
|
||||
|
||||
@@ -21,68 +21,50 @@ import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"k8s.io/apiserver/pkg/authentication/user"
|
||||
"k8s.io/klog"
|
||||
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
||||
"kubesphere.io/kubesphere/pkg/server/errors"
|
||||
"kubesphere.io/kubesphere/pkg/simple/client/cache"
|
||||
"time"
|
||||
)
|
||||
|
||||
const DefaultIssuerName = "kubesphere"
|
||||
|
||||
var (
|
||||
errInvalidToken = errors.New("invalid token")
|
||||
errTokenExpired = errors.New("expired token")
|
||||
const (
|
||||
DefaultIssuerName = "kubesphere"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
Username string `json:"username"`
|
||||
UID string `json:"uid"`
|
||||
Username string `json:"username"`
|
||||
UID string `json:"uid"`
|
||||
TokenType TokenType `json:"token_type"`
|
||||
// Currently, we are not using any field in jwt.StandardClaims
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
type jwtTokenIssuer struct {
|
||||
name string
|
||||
options *authoptions.AuthenticationOptions
|
||||
cache cache.Interface
|
||||
keyFunc jwt.Keyfunc
|
||||
name string
|
||||
secret []byte
|
||||
// Maximum time difference
|
||||
maximumClockSkew time.Duration
|
||||
}
|
||||
|
||||
func (s *jwtTokenIssuer) Verify(tokenString string) (User, error) {
|
||||
if len(tokenString) == 0 {
|
||||
return nil, errInvalidToken
|
||||
}
|
||||
|
||||
func (s *jwtTokenIssuer) Verify(tokenString string) (user.Info, TokenType, error) {
|
||||
clm := &Claims{}
|
||||
// verify token signature and expiration time
|
||||
_, err := jwt.ParseWithClaims(tokenString, clm, s.keyFunc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
klog.Error(err)
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// accessTokenMaxAge = 0 or token without expiration time means that the token will not expire
|
||||
// do not validate token cache
|
||||
if s.options.OAuthOptions.AccessTokenMaxAge > 0 && clm.ExpiresAt > 0 {
|
||||
_, err = s.cache.Get(tokenCacheKey(tokenString))
|
||||
|
||||
if err != nil {
|
||||
if err == cache.ErrNoSuchKey {
|
||||
return nil, errTokenExpired
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &user.DefaultInfo{Name: clm.Username, UID: clm.UID}, nil
|
||||
return &user.DefaultInfo{Name: clm.Username, UID: clm.UID}, clm.TokenType, nil
|
||||
}
|
||||
|
||||
func (s *jwtTokenIssuer) IssueTo(user User, expiresIn time.Duration) (string, error) {
|
||||
func (s *jwtTokenIssuer) IssueTo(user user.Info, tokenType TokenType, expiresIn time.Duration) (string, error) {
|
||||
issueAt := time.Now().Unix() - int64(s.maximumClockSkew.Seconds())
|
||||
notBefore := issueAt
|
||||
clm := &Claims{
|
||||
Username: user.GetName(),
|
||||
UID: user.GetUID(),
|
||||
Username: user.GetName(),
|
||||
UID: user.GetUID(),
|
||||
TokenType: tokenType,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
IssuedAt: time.Now().Unix(),
|
||||
IssuedAt: issueAt,
|
||||
Issuer: s.name,
|
||||
NotBefore: time.Now().Unix(),
|
||||
NotBefore: notBefore,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -92,48 +74,28 @@ func (s *jwtTokenIssuer) IssueTo(user User, expiresIn time.Duration) (string, er
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, clm)
|
||||
|
||||
tokenString, err := token.SignedString([]byte(s.options.JwtSecret))
|
||||
tokenString, err := token.SignedString(s.secret)
|
||||
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 0 means no expiration.
|
||||
// validate token cache
|
||||
if s.options.OAuthOptions.AccessTokenMaxAge > 0 {
|
||||
err = s.cache.Set(tokenCacheKey(tokenString), tokenString, s.options.OAuthOptions.AccessTokenMaxAge)
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
func (s *jwtTokenIssuer) Revoke(token string) error {
|
||||
if s.options.OAuthOptions.AccessTokenMaxAge > 0 {
|
||||
return s.cache.Del(tokenCacheKey(token))
|
||||
func (s *jwtTokenIssuer) keyFunc(token *jwt.Token) (i interface{}, err error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
|
||||
return s.secret, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("expect token signed with HMAC but got %v", token.Header["alg"])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewJwtTokenIssuer(issuerName string, options *authoptions.AuthenticationOptions, cache cache.Interface) Issuer {
|
||||
func NewTokenIssuer(secret string, maximumClockSkew time.Duration) Issuer {
|
||||
return &jwtTokenIssuer{
|
||||
name: issuerName,
|
||||
options: options,
|
||||
cache: cache,
|
||||
keyFunc: func(token *jwt.Token) (i interface{}, err error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
|
||||
return []byte(options.JwtSecret), nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("expect token signed with HMAC but got %v", token.Header["alg"])
|
||||
}
|
||||
},
|
||||
name: DefaultIssuerName,
|
||||
secret: []byte(secret),
|
||||
maximumClockSkew: maximumClockSkew,
|
||||
}
|
||||
}
|
||||
|
||||
func tokenCacheKey(token string) string {
|
||||
return fmt.Sprintf("kubesphere:tokens:%s", token)
|
||||
}
|
||||
|
||||
@@ -19,89 +19,30 @@ package token
|
||||
import (
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"k8s.io/apiserver/pkg/authentication/user"
|
||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
||||
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
||||
"kubesphere.io/kubesphere/pkg/simple/client/cache"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJwtTokenIssuer(t *testing.T) {
|
||||
options := authoptions.NewAuthenticateOptions()
|
||||
options.JwtSecret = "kubesphere"
|
||||
issuer := NewJwtTokenIssuer(DefaultIssuerName, options, cache.NewSimpleCache())
|
||||
|
||||
testCases := []struct {
|
||||
description string
|
||||
name string
|
||||
uid string
|
||||
email string
|
||||
}{
|
||||
{
|
||||
name: "admin",
|
||||
uid: "b8be6edd-2c92-4535-9b2a-df6326474458",
|
||||
},
|
||||
{
|
||||
name: "bar",
|
||||
uid: "b8be6edd-2c92-4535-9b2a-df6326474452",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
user := &user.DefaultInfo{
|
||||
Name: testCase.name,
|
||||
UID: testCase.uid,
|
||||
}
|
||||
|
||||
t.Run(testCase.description, func(t *testing.T) {
|
||||
token, err := issuer.IssueTo(user, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := issuer.Verify(token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(user, got); len(diff) != 0 {
|
||||
t.Errorf("%T differ (-got, +expected), %s", user, diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenVerifyWithoutCacheValidate(t *testing.T) {
|
||||
options := authoptions.NewAuthenticateOptions()
|
||||
|
||||
// do not set token cache and disable token cache validate,
|
||||
options.OAuthOptions = &oauth.Options{AccessTokenMaxAge: 0}
|
||||
options.JwtSecret = "kubesphere"
|
||||
issuer := NewJwtTokenIssuer(DefaultIssuerName, options, nil)
|
||||
issuer := NewTokenIssuer("kubesphere", 0)
|
||||
|
||||
client, err := options.OAuthOptions.OAuthClient("default")
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
user := &user.DefaultInfo{
|
||||
admin := &user.DefaultInfo{
|
||||
Name: "admin",
|
||||
UID: "admin",
|
||||
}
|
||||
|
||||
tokenString, err := issuer.IssueTo(user, *client.AccessTokenMaxAge)
|
||||
tokenString, err := issuer.IssueTo(admin, AccessToken, 0)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := issuer.Verify(tokenString)
|
||||
got, _, err := issuer.Verify(tokenString)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(got, user); diff != "" {
|
||||
if diff := cmp.Diff(got, admin); diff != "" {
|
||||
t.Error("token validate failed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The KubeSphere Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package token
|
||||
|
||||
type User interface {
|
||||
// Name
|
||||
GetName() string
|
||||
|
||||
// UID
|
||||
GetUID() string
|
||||
}
|
||||
Reference in New Issue
Block a user