From 96a1d3825e8e1064f5de36ad38bbafe9ee0b9b93 Mon Sep 17 00:00:00 2001 From: hongming Date: Thu, 26 Mar 2020 18:42:01 +0800 Subject: [PATCH] update Signed-off-by: hongming --- pkg/apiserver/apiserver.go | 6 +- .../github}/github.go | 43 ++++++++++++- .../identityprovider/identity_provider.go | 42 ++++++++++++- .../authentication/oauth/oauth_options.go | 59 ++++++++---------- pkg/apiserver/authentication/token/issuer.go | 4 +- pkg/apiserver/authentication/token/jwt.go | 8 +-- pkg/apiserver/config/config_test.go | 61 +++++++++++-------- pkg/kapis/oauth/handler.go | 19 +++--- pkg/kapis/oauth/register.go | 16 ++++- .../serverconfig/{ => v1alpha2}/register.go | 22 ++++--- 10 files changed, 187 insertions(+), 93 deletions(-) rename pkg/apiserver/authentication/{oauth => identityprovider/github}/github.go (83%) rename pkg/kapis/serverconfig/{ => v1alpha2}/register.go (66%) diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index c39a7be5e..87ae92da4 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -33,7 +33,7 @@ import ( operationsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/operations/v1alpha2" resourcesv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha2" resourcev1alpha3 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha3" - "kubesphere.io/kubesphere/pkg/kapis/serverconfig" + "kubesphere.io/kubesphere/pkg/kapis/serverconfig/v1alpha2" servicemeshv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/servicemesh/metrics/v1alpha2" terminalv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/terminal/v1alpha2" "kubesphere.io/kubesphere/pkg/models/iam/am" @@ -133,7 +133,7 @@ func (s *APIServer) PrepareRun() error { } func (s *APIServer) installKubeSphereAPIs() { - urlruntime.Must(serverconfig.AddToContainer(s.container, s.Config)) + urlruntime.Must(v1alpha2.AddToContainer(s.container, s.Config)) urlruntime.Must(resourcev1alpha3.AddToContainer(s.container, s.InformerFactory)) // Need to refactor devops api registration, too much dependencies //urlruntime.Must(devopsv1alpha2.AddToContainer(s.container, s.DevopsClient, s.DBClient.Database(), nil, s.KubernetesClient.KubeSphere(), s.InformerFactory.KubeSphereSharedInformerFactory(), s.S3Client)) @@ -185,7 +185,7 @@ func (s *APIServer) buildHandlerChain() { handler = filters.WithKubeAPIServer(handler, s.KubernetesClient.Config(), &errorResponder{}) handler = filters.WithMultipleClusterDispatcher(handler, dispatch.DefaultClusterDispatch) - excludedPaths := []string{"/oauth/*", "/server/configs/*"} + excludedPaths := []string{"/oauth/*", "/kapis/config.kubesphere.io/*"} pathAuthorizer, _ := path.NewAuthorizer(excludedPaths) authorizer := unionauthorizer.New(pathAuthorizer, authorizerfactory.NewOPAAuthorizer(am.NewFakeAMOperator())) diff --git a/pkg/apiserver/authentication/oauth/github.go b/pkg/apiserver/authentication/identityprovider/github/github.go similarity index 83% rename from pkg/apiserver/authentication/oauth/github.go rename to pkg/apiserver/authentication/identityprovider/github/github.go index ac12c13c2..580b73f1d 100644 --- a/pkg/apiserver/authentication/oauth/github.go +++ b/pkg/apiserver/authentication/identityprovider/github/github.go @@ -16,14 +16,17 @@ * / */ -package oauth +package github import ( "context" "encoding/json" "golang.org/x/oauth2" + "gopkg.in/yaml.v2" "io/ioutil" "k8s.io/apiserver/pkg/authentication/user" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth" "time" ) @@ -98,6 +101,44 @@ type GithubIdentity struct { Collaborators int `json:"collaborators"` } +func init() { + identityprovider.RegisterOAuthProviderCodec(&codec{t: "github"}) +} + +type codec struct { + t string +} + +func (c codec) Type() string { + return c.t +} + +func (codec) Encode(provider identityprovider.OAuthProvider) (*oauth.DynamicOptions, error) { + data, err := yaml.Marshal(provider) + if err != nil { + return nil, err + } + var options oauth.DynamicOptions + err = yaml.Unmarshal(data, &options) + if err != nil { + return nil, err + } + return &options, nil +} + +func (codec) Decode(options *oauth.DynamicOptions) (identityprovider.OAuthProvider, error) { + data, err := yaml.Marshal(options) + if err != nil { + return nil, err + } + var provider Github + err = yaml.Unmarshal(data, &provider) + if err != nil { + return nil, err + } + return &provider, nil +} + func (g GithubIdentity) GetName() string { return g.Login } diff --git a/pkg/apiserver/authentication/identityprovider/identity_provider.go b/pkg/apiserver/authentication/identityprovider/identity_provider.go index 7601723a4..1a5a4c262 100644 --- a/pkg/apiserver/authentication/identityprovider/identity_provider.go +++ b/pkg/apiserver/authentication/identityprovider/identity_provider.go @@ -18,8 +18,46 @@ package identityprovider -import "k8s.io/apiserver/pkg/authentication/user" +import ( + "errors" + "k8s.io/apiserver/pkg/authentication/user" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth" +) -type OAuth2Interface interface { +var ( + ErrorIdentityProviderNotFound = errors.New("the identity provider was not found") + ErrorAlreadyRegistered = errors.New("the identity provider was not found") + oauthProviderCodecs = map[string]OAuthProviderCodec{} +) + +type OAuthProvider interface { IdentityExchange(code string) (user.Info, error) } + +type OAuthProviderCodec interface { + Type() string + Decode(options *oauth.DynamicOptions) (OAuthProvider, error) + Encode(provider OAuthProvider) (*oauth.DynamicOptions, error) +} + +func ResolveOAuthProvider(providerType string, options *oauth.DynamicOptions) (OAuthProvider, error) { + if codec, ok := oauthProviderCodecs[providerType]; ok { + return codec.Decode(options) + } + return nil, ErrorIdentityProviderNotFound +} + +func ResolveOAuthOptions(providerType string, provider OAuthProvider) (*oauth.DynamicOptions, error) { + if codec, ok := oauthProviderCodecs[providerType]; ok { + return codec.Encode(provider) + } + return nil, ErrorIdentityProviderNotFound +} + +func RegisterOAuthProviderCodec(codec OAuthProviderCodec) error { + if _, ok := oauthProviderCodecs[codec.Type()]; ok { + return ErrorAlreadyRegistered + } + oauthProviderCodecs[codec.Type()] = codec + return nil +} diff --git a/pkg/apiserver/authentication/oauth/oauth_options.go b/pkg/apiserver/authentication/oauth/oauth_options.go index 2d0c441ee..554d7b966 100644 --- a/pkg/apiserver/authentication/oauth/oauth_options.go +++ b/pkg/apiserver/authentication/oauth/oauth_options.go @@ -20,8 +20,8 @@ package oauth import ( "errors" - "kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider" "kubesphere.io/kubesphere/pkg/utils/sliceutil" + "time" ) type GrantHandlerType string @@ -43,26 +43,23 @@ const ( MappingMethodLookup MappingMethod = "lookup" // MappingMethodMixed A user entity can be mapped with multiple identifyProvider. MappingMethodMixed MappingMethod = "mixed" - - IdentityProviderTypeGithub = "github" ) var ( - ErrorClientNotFound = errors.New("the OAuth client was not found") - ErrorRedirectURLNotAllowed = errors.New("redirect URL is not allowed") - ErrorIdentityProviderNotFound = errors.New("the identity provider was not found") + ErrorClientNotFound = errors.New("the OAuth client was not found") + ErrorRedirectURLNotAllowed = errors.New("redirect URL is not allowed") ) type Options struct { // LDAPPasswordIdentityProvider provider is used by default. - IdentityProviders []IdentityProvider `json:"identityProviders,omitempty" yaml:"identityProviders,omitempty"` + IdentityProviders []IdentityProviderOptions `json:"identityProviders,omitempty" yaml:"identityProviders,omitempty"` // Register additional OAuth clients. Clients []Client `json:"clients,omitempty" yaml:"clients,omitempty"` // AccessTokenMaxAgeSeconds control the lifetime of access tokens. The default lifetime is 24 hours. // 0 means no expiration. - AccessTokenMaxAgeSeconds int `json:"accessTokenMaxAgeSeconds" yaml:"accessTokenMaxAgeSeconds"` + AccessTokenMaxAge time.Duration `json:"accessTokenMaxAge" yaml:"accessTokenMaxAge"` // Inactivity timeout for tokens // The value represents the maximum amount of time that can occur between @@ -72,12 +69,14 @@ type Options struct { // This value needs to be set only if the default set in configuration is // not appropriate for this client. Valid values are: // - 0: Tokens for this client never time out - // - X: Tokens time out if there is no activity for X seconds - // The current minimum allowed value for X is 300 (5 minutes) - AccessTokenInactivityTimeoutSeconds int `json:"accessTokenInactivityTimeoutSeconds" yaml:"accessTokenInactivityTimeoutSeconds"` + // - X: Tokens time out if there is no activity + // The current minimum allowed value for X is 5 minutes + AccessTokenInactivityTimeout time.Duration `json:"accessTokenInactivityTimeout" yaml:"accessTokenInactivityTimeout"` } -type IdentityProvider struct { +type DynamicOptions map[string]interface{} + +type IdentityProviderOptions struct { // The provider name. Name string `json:"name" yaml:"name"` @@ -96,8 +95,8 @@ type IdentityProvider struct { // The type of identify provider Type string `json:"type" yaml:"type"` - // Provider options - Github *Github `json:"github" yaml:"github" ` + // The options of identify provider + Provider *DynamicOptions `json:"provider,omitempty" yaml:"provider,omitempty"` } type Token struct { @@ -145,15 +144,15 @@ type Client struct { // If no restriction matches, then the scope is denied. ScopeRestrictions []string `json:"scopeRestrictions,omitempty" yaml:"scopeRestrictions,omitempty"` - // AccessTokenMaxAgeSeconds overrides the default access token max age for tokens granted to this client. - AccessTokenMaxAgeSeconds *int `json:"accessTokenMaxAgeSeconds,omitempty" yaml:"accessTokenMaxAgeSeconds,omitempty"` + // AccessTokenMaxAge overrides the default access token max age for tokens granted to this client. + AccessTokenMaxAge *time.Duration `json:"accessTokenMaxAge,omitempty" yaml:"accessTokenMaxAge,omitempty"` - // AccessTokenInactivityTimeoutSeconds overrides the default token + // AccessTokenInactivityTimeout overrides the default token // inactivity timeout for tokens granted to this client. - AccessTokenInactivityTimeoutSeconds *int `json:"accessTokenInactivityTimeoutSeconds,omitempty" yaml:"accessTokenInactivityTimeoutSeconds,omitempty"` + AccessTokenInactivityTimeout *time.Duration `json:"accessTokenInactivityTimeout,omitempty" yaml:"accessTokenInactivityTimeout,omitempty"` } -func (o *Options) GetOAuthClient(name string) (Client, error) { +func (o *Options) OAuthClient(name string) (Client, error) { for _, found := range o.Clients { if found.Name == name { return found, nil @@ -161,13 +160,13 @@ func (o *Options) GetOAuthClient(name string) (Client, error) { } return Client{}, ErrorClientNotFound } -func (o *Options) GetIdentityProvider(name string) (IdentityProvider, error) { +func (o *Options) IdentityProviderOptions(name string) (IdentityProviderOptions, error) { for _, found := range o.IdentityProviders { if found.Name == name { return found, nil } } - return IdentityProvider{}, ErrorClientNotFound + return IdentityProviderOptions{}, ErrorClientNotFound } func (c Client) ResolveRedirectURL(expectURL string) (string, error) { @@ -183,21 +182,11 @@ func (c Client) ResolveRedirectURL(expectURL string) (string, error) { return "", ErrorRedirectURLNotAllowed } -func (i IdentityProvider) GetOAuth2IdentityProviderInstance() (identityprovider.OAuth2Interface, error) { - switch i.Type { - case IdentityProviderTypeGithub: - if i.Github != nil { - return i.Github, nil - } - } - return nil, ErrorIdentityProviderNotFound -} - func NewOptions() *Options { return &Options{ - IdentityProviders: make([]IdentityProvider, 0), - Clients: make([]Client, 0), - AccessTokenMaxAgeSeconds: 86400, - AccessTokenInactivityTimeoutSeconds: 0, + IdentityProviders: make([]IdentityProviderOptions, 0), + Clients: make([]Client, 0), + AccessTokenMaxAge: time.Hour * 24, + AccessTokenInactivityTimeout: 0, } } diff --git a/pkg/apiserver/authentication/token/issuer.go b/pkg/apiserver/authentication/token/issuer.go index 65eab50d4..1661592ca 100644 --- a/pkg/apiserver/authentication/token/issuer.go +++ b/pkg/apiserver/authentication/token/issuer.go @@ -18,10 +18,12 @@ package token +import "time" + // 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, expiresInSecond int) (string, error) + IssueTo(user User, 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) diff --git a/pkg/apiserver/authentication/token/jwt.go b/pkg/apiserver/authentication/token/jwt.go index b6b6881f1..ff2b18caf 100644 --- a/pkg/apiserver/authentication/token/jwt.go +++ b/pkg/apiserver/authentication/token/jwt.go @@ -72,7 +72,7 @@ func (s *jwtTokenIssuer) Verify(tokenString string) (User, error) { return &iam.User{Name: clm.Username, UID: clm.UID}, nil } -func (s *jwtTokenIssuer) IssueTo(user User, expiresInSecond int) (string, error) { +func (s *jwtTokenIssuer) IssueTo(user User, expiresIn time.Duration) (string, error) { clm := &Claims{ Username: user.GetName(), UID: user.GetUID(), @@ -83,8 +83,8 @@ func (s *jwtTokenIssuer) IssueTo(user User, expiresInSecond int) (string, error) }, } - if expiresInSecond > 0 { - clm.ExpiresAt = clm.IssuedAt + int64(expiresInSecond) + if expiresIn > 0 { + clm.ExpiresAt = clm.IssuedAt + int64(expiresIn.Seconds()) } token := jwt.NewWithClaims(jwt.SigningMethodHS256, clm) @@ -95,7 +95,7 @@ func (s *jwtTokenIssuer) IssueTo(user User, expiresInSecond int) (string, error) return "", err } - s.cache.Set(tokenCacheKey(tokenString), tokenString, time.Second*time.Duration(expiresInSecond)) + s.cache.Set(tokenCacheKey(tokenString), tokenString, expiresIn) return tokenString, nil } diff --git a/pkg/apiserver/config/config_test.go b/pkg/apiserver/config/config_test.go index dca9d8009..42ec60fc2 100644 --- a/pkg/apiserver/config/config_test.go +++ b/pkg/apiserver/config/config_test.go @@ -5,6 +5,8 @@ import ( "github.com/google/go-cmp/cmp" "gopkg.in/yaml.v2" "io/ioutil" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider/github" "kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth" authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options" "kubesphere.io/kubesphere/pkg/simple/client/alerting" @@ -20,13 +22,26 @@ import ( "kubesphere.io/kubesphere/pkg/simple/client/s3" "kubesphere.io/kubesphere/pkg/simple/client/servicemesh" "kubesphere.io/kubesphere/pkg/simple/client/sonarqube" - "kubesphere.io/kubesphere/pkg/utils/reflectutils" "os" "testing" "time" ) -func newTestConfig() *Config { +func newTestConfig() (*Config, error) { + + githubOAuthProvider, err := identityprovider.ResolveOAuthOptions("github", &github.Github{ + ClientID: "de6ff7bed0304e487b6e", + ClientSecret: "xxxxxx-xxxxx-xxxxx", + Endpoint: github.Endpoint{ + AuthURL: "https://github.com/login/oauth/authorize", + TokenURL: "https://github.com/login/oauth/token", + }, + RedirectURL: "https://ks-console.kubesphere-system.svc/oauth/callbak/github", + Scopes: []string{"user"}, + }) + if err != nil { + return nil, err + } var conf = &Config{ MySQLOptions: &mysql.Options{ Host: "10.68.96.5:3306", @@ -110,36 +125,27 @@ func newTestConfig() *Config { JwtSecret: "xxxxxx", MultipleLogin: false, OAuthOptions: &oauth.Options{ - IdentityProviders: []oauth.IdentityProvider{{ + IdentityProviders: []oauth.IdentityProviderOptions{{ Name: "github", MappingMethod: "auto", LoginRedirect: true, - Type: oauth.IdentityProviderTypeGithub, - Github: &oauth.Github{ - ClientID: "de6ff7bed0304e487b6e", - ClientSecret: "xxxxxx-xxxxx-xxxxx", - Endpoint: oauth.Endpoint{ - AuthURL: "https://github.com/login/oauth/authorize", - TokenURL: "https://github.com/login/oauth/token", - }, - RedirectURL: "https://ks-console.kubesphere-system.svc/oauth/callbak/github", - Scopes: []string{"user"}, - }, + Type: "github", + Provider: githubOAuthProvider, }}, Clients: []oauth.Client{{ - Name: "kubesphere-console-client", - Secret: "xxxxxx-xxxxxx-xxxxxx", - RespondWithChallenges: true, - RedirectURIs: []string{"http://ks-console.kubesphere-system.svc/oauth/token/implicit"}, - GrantMethod: oauth.GrantHandlerAuto, - AccessTokenInactivityTimeoutSeconds: nil, + Name: "kubesphere-console-client", + Secret: "xxxxxx-xxxxxx-xxxxxx", + RespondWithChallenges: true, + RedirectURIs: []string{"http://ks-console.kubesphere-system.svc/oauth/token/implicit"}, + GrantMethod: oauth.GrantHandlerAuto, + AccessTokenInactivityTimeout: nil, }}, - AccessTokenMaxAgeSeconds: 86400, - AccessTokenInactivityTimeoutSeconds: 0, + AccessTokenMaxAge: time.Hour * 24, + AccessTokenInactivityTimeout: 0, }, }, } - return conf + return conf, nil } func saveTestConfig(t *testing.T, conf *Config) { @@ -147,7 +153,6 @@ func saveTestConfig(t *testing.T, conf *Config) { if err != nil { t.Fatalf("error marshal config. %v", err) } - err = ioutil.WriteFile(fmt.Sprintf("%s.yaml", defaultConfigurationName), content, 0640) if err != nil { t.Fatalf("error write configuration file, %v", err) @@ -169,7 +174,10 @@ func cleanTestConfig(t *testing.T) { } func TestGet(t *testing.T) { - conf := newTestConfig() + conf, err := newTestConfig() + if err != nil { + t.Fatal(err) + } saveTestConfig(t, conf) defer cleanTestConfig(t) @@ -178,8 +186,7 @@ func TestGet(t *testing.T) { t.Fatal(err) } - cmp.Diff(conf, conf2) - if diff := reflectutils.Equal(conf, conf2); diff != nil { + if diff := cmp.Diff(conf, conf2); diff != "" { t.Fatal(diff) } } diff --git a/pkg/kapis/oauth/handler.go b/pkg/kapis/oauth/handler.go index b673aa456..bab48cd0f 100644 --- a/pkg/kapis/oauth/handler.go +++ b/pkg/kapis/oauth/handler.go @@ -25,6 +25,7 @@ import ( "k8s.io/klog" "kubesphere.io/kubesphere/pkg/api" "kubesphere.io/kubesphere/pkg/api/auth" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider" "kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth" authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options" "kubesphere.io/kubesphere/pkg/apiserver/authentication/token" @@ -85,7 +86,7 @@ func (h *oauthHandler) AuthorizeHandler(req *restful.Request, resp *restful.Resp responseType := req.QueryParameter("response_type") redirectURI := req.QueryParameter("redirect_uri") - conf, err := h.options.OAuthOptions.GetOAuthClient(clientId) + conf, err := h.options.OAuthOptions.OAuthClient(clientId) if err != nil { err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err)) @@ -105,10 +106,10 @@ func (h *oauthHandler) AuthorizeHandler(req *restful.Request, resp *restful.Resp return } - expiresIn := h.options.OAuthOptions.AccessTokenMaxAgeSeconds + expiresIn := h.options.OAuthOptions.AccessTokenMaxAge - if conf.AccessTokenMaxAgeSeconds != nil { - expiresIn = *conf.AccessTokenMaxAgeSeconds + if conf.AccessTokenMaxAge != nil { + expiresIn = *conf.AccessTokenMaxAge } accessToken, err := h.issuer.IssueTo(user, expiresIn) @@ -130,7 +131,7 @@ func (h *oauthHandler) AuthorizeHandler(req *restful.Request, resp *restful.Resp redirectURL = fmt.Sprintf("%s#access_token=%s&token_type=Bearer", redirectURL, accessToken) if expiresIn > 0 { - redirectURL = fmt.Sprintf("%s&expires_in=%v", redirectURL, expiresIn) + redirectURL = fmt.Sprintf("%s&expires_in=%v", redirectURL, expiresIn.Seconds()) } resp.Header().Set("Content-Type", "text/plain") @@ -147,14 +148,14 @@ func (h *oauthHandler) OAuthCallBackHandler(req *restful.Request, resp *restful. resp.WriteError(http.StatusUnauthorized, err) } - idP, err := h.options.OAuthOptions.GetIdentityProvider(name) + idP, err := h.options.OAuthOptions.IdentityProviderOptions(name) if err != nil { err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err)) resp.WriteError(http.StatusUnauthorized, err) } - oauthIdentityProvider, err := idP.GetOAuth2IdentityProviderInstance() + oauthIdentityProvider, err := identityprovider.ResolveOAuthProvider(idP.Type, idP.Provider) if err != nil { err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err)) @@ -168,7 +169,7 @@ func (h *oauthHandler) OAuthCallBackHandler(req *restful.Request, resp *restful. resp.WriteError(http.StatusUnauthorized, err) } - expiresIn := h.options.OAuthOptions.AccessTokenMaxAgeSeconds + expiresIn := h.options.OAuthOptions.AccessTokenMaxAge accessToken, err := h.issuer.IssueTo(user, expiresIn) @@ -181,7 +182,7 @@ func (h *oauthHandler) OAuthCallBackHandler(req *restful.Request, resp *restful. result := oauth.Token{ AccessToken: accessToken, TokenType: "Bearer", - ExpiresIn: expiresIn, + ExpiresIn: int(expiresIn.Seconds()), } resp.WriteEntity(result) diff --git a/pkg/kapis/oauth/register.go b/pkg/kapis/oauth/register.go index 85b2de12c..e27e9b74e 100644 --- a/pkg/kapis/oauth/register.go +++ b/pkg/kapis/oauth/register.go @@ -23,12 +23,19 @@ import ( restfulspec "github.com/emicklei/go-restful-openapi" "kubesphere.io/kubesphere/pkg/api" "kubesphere.io/kubesphere/pkg/api/auth" + "kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth" authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options" "kubesphere.io/kubesphere/pkg/apiserver/authentication/token" "kubesphere.io/kubesphere/pkg/constants" "net/http" ) +// ks-apiserver includes a built-in OAuth server. Users obtain OAuth access tokens to authenticate themselves to the API. +// The OAuth server supports standard authorization code grant and the implicit grant OAuth authorization flows. +// All requests for OAuth tokens involve a request to /oauth/authorize. +// Most authentication integrations place an authenticating proxy in front of this endpoint, or configure ks-apiserver +// to validate credentials against a backing identity provider. +// Requests to /oauth/authorize can come from user-agents that cannot display interactive login pages, such as the CLI. func AddToContainer(c *restful.Container, issuer token.Issuer, options *authoptions.AuthenticationOptions) error { ws := &restful.WebService{} ws.Path("/oauth"). @@ -48,12 +55,17 @@ func AddToContainer(c *restful.Container, issuer token.Issuer, options *authopti // Only support implicit grant flow // https://tools.ietf.org/html/rfc6749#section-4.2 - // curl -u admin:P@88w0rd 'http://ks-apiserver.kubesphere-system.svc/oauth/authorize?client_id=kubesphere-console-client&response_type=token' -v ws.Route(ws.GET("/authorize"). + Doc("All requests for OAuth tokens involve a request to /oauth/authorize."). To(handler.AuthorizeHandler)) //ws.Route(ws.POST("/token")) + + // Authorization callback URL, where the end of the URL contains the identity provider name. + // The provider name is also used to build the callback URL. ws.Route(ws.GET("/callback/{callback}"). - To(handler.OAuthCallBackHandler)) + Doc("OAuth callback API, the path param callback is config by identity provider"). + To(handler.OAuthCallBackHandler). + Returns(http.StatusOK, api.StatusOK, oauth.Token{})) c.Add(ws) diff --git a/pkg/kapis/serverconfig/register.go b/pkg/kapis/serverconfig/v1alpha2/register.go similarity index 66% rename from pkg/kapis/serverconfig/register.go rename to pkg/kapis/serverconfig/v1alpha2/register.go index 1a68bd924..739a31c02 100644 --- a/pkg/kapis/serverconfig/register.go +++ b/pkg/kapis/serverconfig/v1alpha2/register.go @@ -16,30 +16,34 @@ * / */ -package serverconfig +package v1alpha2 import ( "github.com/emicklei/go-restful" + "k8s.io/apimachinery/pkg/runtime/schema" apiserverconfig "kubesphere.io/kubesphere/pkg/apiserver/config" + "kubesphere.io/kubesphere/pkg/apiserver/runtime" ) -func AddToContainer(c *restful.Container, config *apiserverconfig.Config) error { - configs := &restful.WebService{} +const ( + GroupName = "config.kubesphere.io" +) - configs.Path("/server/configs"). - Consumes(restful.MIME_JSON). - Produces(restful.MIME_JSON) +var GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha2"} + +func AddToContainer(c *restful.Container, config *apiserverconfig.Config) error { + webservice := runtime.NewWebService(GroupVersion) // information about the authorization server are published. - configs.Route(configs.GET("/oauth-configz").To(func(request *restful.Request, response *restful.Response) { + webservice.Route(webservice.GET("/configs/oauth").To(func(request *restful.Request, response *restful.Response) { response.WriteEntity(config.AuthenticationOptions.OAuthOptions) })) // information about the server configuration - configs.Route(configs.GET("/configz").To(func(request *restful.Request, response *restful.Response) { + webservice.Route(webservice.GET("/configs/configz").To(func(request *restful.Request, response *restful.Response) { response.WriteAsJson(config.ToMap()) })) - c.Add(configs) + c.Add(webservice) return nil }