fix cannot create success login (#2576)

Signed-off-by: Jeff <zw0948@gmail.com>
This commit is contained in:
zryfish
2020-07-24 13:09:38 +08:00
committed by GitHub
parent 06932926a0
commit f1146f5d6c
23 changed files with 2183 additions and 271 deletions

View File

@@ -26,12 +26,16 @@ import (
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
"k8s.io/klog"
iamv1alpha2 "kubesphere.io/kubesphere/pkg/apis/iam/v1alpha2"
"kubesphere.io/kubesphere/pkg/apiserver/request"
"kubesphere.io/kubesphere/pkg/models/iam/im"
"net/http"
"strings"
)
// WithAuthentication installs authentication handler to handler chain.
// The following part is a little bit ugly, WithAuthentication also logs user failed login attempt
// if using basic auth. But only treats request with requestURI `/oauth/authorize` as login attempt
func WithAuthentication(handler http.Handler, auth authenticator.Request, loginRecorder im.LoginRecorder) http.Handler {
if auth == nil {
klog.Warningf("Authentication is disabled")
@@ -41,15 +45,24 @@ func WithAuthentication(handler http.Handler, auth authenticator.Request, loginR
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
resp, ok, err := auth.AuthenticateRequest(req)
username, _, usingBasicAuth := req.BasicAuth()
defer func() {
// if we authenticated successfully, go ahead and remove the bearer token so that no one
// is ever tempted to use it inside of the API server
if usingBasicAuth && ok {
req.Header.Del("Authorization")
}
}()
if err != nil || !ok {
if err != nil {
klog.Errorf("Unable to authenticate the request due to error: %v", err)
if err.Error() == im.AuthFailedIncorrectPassword.Error() { // log failed login attempts
username, _, _ := req.BasicAuth()
if usingBasicAuth { // log failed login attempts
go func(user string) {
if loginRecorder != nil && len(user) != 0 {
err = loginRecorder.RecordLogin(user, err, req)
klog.Errorf("Failed to record unsuccessful login attempt for user %s", user)
err = loginRecorder.RecordLogin(user, iamv1alpha2.BasicAuth, "", err, req)
klog.Errorf("Failed to record unsuccessful login attempt for user %s, error: %v", user, err)
}
}(username)
}
@@ -67,6 +80,13 @@ func WithAuthentication(handler http.Handler, auth authenticator.Request, loginR
return
}
go func() {
if loginRecorder != nil && usingBasicAuth && strings.HasPrefix(req.URL.Path, "/oauth/authorize") {
err = loginRecorder.RecordLogin(username, iamv1alpha2.BasicAuth, "", nil, req)
klog.Errorf("Failed to record unsuccessful login attempt for user %s, error: %v", username, err)
}
}()
req = req.WithContext(request.WithUser(req.Context(), resp.User))
handler.ServeHTTP(w, req)
})