@@ -33,7 +33,7 @@ import (
|
|||||||
operationsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/operations/v1alpha2"
|
operationsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/operations/v1alpha2"
|
||||||
resourcesv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha2"
|
resourcesv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha2"
|
||||||
resourcev1alpha3 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha3"
|
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"
|
servicemeshv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/servicemesh/metrics/v1alpha2"
|
||||||
terminalv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/terminal/v1alpha2"
|
terminalv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/terminal/v1alpha2"
|
||||||
"kubesphere.io/kubesphere/pkg/models/iam/am"
|
"kubesphere.io/kubesphere/pkg/models/iam/am"
|
||||||
@@ -133,7 +133,7 @@ func (s *APIServer) PrepareRun() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *APIServer) installKubeSphereAPIs() {
|
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))
|
urlruntime.Must(resourcev1alpha3.AddToContainer(s.container, s.InformerFactory))
|
||||||
// Need to refactor devops api registration, too much dependencies
|
// 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))
|
//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.WithKubeAPIServer(handler, s.KubernetesClient.Config(), &errorResponder{})
|
||||||
handler = filters.WithMultipleClusterDispatcher(handler, dispatch.DefaultClusterDispatch)
|
handler = filters.WithMultipleClusterDispatcher(handler, dispatch.DefaultClusterDispatch)
|
||||||
|
|
||||||
excludedPaths := []string{"/oauth/*", "/server/configs/*"}
|
excludedPaths := []string{"/oauth/*", "/kapis/config.kubesphere.io/*"}
|
||||||
pathAuthorizer, _ := path.NewAuthorizer(excludedPaths)
|
pathAuthorizer, _ := path.NewAuthorizer(excludedPaths)
|
||||||
authorizer := unionauthorizer.New(pathAuthorizer,
|
authorizer := unionauthorizer.New(pathAuthorizer,
|
||||||
authorizerfactory.NewOPAAuthorizer(am.NewFakeAMOperator()))
|
authorizerfactory.NewOPAAuthorizer(am.NewFakeAMOperator()))
|
||||||
|
|||||||
@@ -16,14 +16,17 @@
|
|||||||
* /
|
* /
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package oauth
|
package github
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"k8s.io/apiserver/pkg/authentication/user"
|
"k8s.io/apiserver/pkg/authentication/user"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -98,6 +101,44 @@ type GithubIdentity struct {
|
|||||||
Collaborators int `json:"collaborators"`
|
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 {
|
func (g GithubIdentity) GetName() string {
|
||||||
return g.Login
|
return g.Login
|
||||||
}
|
}
|
||||||
@@ -18,8 +18,46 @@
|
|||||||
|
|
||||||
package identityprovider
|
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)
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ package oauth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"
|
|
||||||
"kubesphere.io/kubesphere/pkg/utils/sliceutil"
|
"kubesphere.io/kubesphere/pkg/utils/sliceutil"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GrantHandlerType string
|
type GrantHandlerType string
|
||||||
@@ -43,26 +43,23 @@ const (
|
|||||||
MappingMethodLookup MappingMethod = "lookup"
|
MappingMethodLookup MappingMethod = "lookup"
|
||||||
// MappingMethodMixed A user entity can be mapped with multiple identifyProvider.
|
// MappingMethodMixed A user entity can be mapped with multiple identifyProvider.
|
||||||
MappingMethodMixed MappingMethod = "mixed"
|
MappingMethodMixed MappingMethod = "mixed"
|
||||||
|
|
||||||
IdentityProviderTypeGithub = "github"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrorClientNotFound = errors.New("the OAuth client was not found")
|
ErrorClientNotFound = errors.New("the OAuth client was not found")
|
||||||
ErrorRedirectURLNotAllowed = errors.New("redirect URL is not allowed")
|
ErrorRedirectURLNotAllowed = errors.New("redirect URL is not allowed")
|
||||||
ErrorIdentityProviderNotFound = errors.New("the identity provider was not found")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
// LDAPPasswordIdentityProvider provider is used by default.
|
// 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.
|
// Register additional OAuth clients.
|
||||||
Clients []Client `json:"clients,omitempty" yaml:"clients,omitempty"`
|
Clients []Client `json:"clients,omitempty" yaml:"clients,omitempty"`
|
||||||
|
|
||||||
// AccessTokenMaxAgeSeconds control the lifetime of access tokens. The default lifetime is 24 hours.
|
// AccessTokenMaxAgeSeconds control the lifetime of access tokens. The default lifetime is 24 hours.
|
||||||
// 0 means no expiration.
|
// 0 means no expiration.
|
||||||
AccessTokenMaxAgeSeconds int `json:"accessTokenMaxAgeSeconds" yaml:"accessTokenMaxAgeSeconds"`
|
AccessTokenMaxAge time.Duration `json:"accessTokenMaxAge" yaml:"accessTokenMaxAge"`
|
||||||
|
|
||||||
// Inactivity timeout for tokens
|
// Inactivity timeout for tokens
|
||||||
// The value represents the maximum amount of time that can occur between
|
// 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
|
// This value needs to be set only if the default set in configuration is
|
||||||
// not appropriate for this client. Valid values are:
|
// not appropriate for this client. Valid values are:
|
||||||
// - 0: Tokens for this client never time out
|
// - 0: Tokens for this client never time out
|
||||||
// - X: Tokens time out if there is no activity for X seconds
|
// - X: Tokens time out if there is no activity
|
||||||
// The current minimum allowed value for X is 300 (5 minutes)
|
// The current minimum allowed value for X is 5 minutes
|
||||||
AccessTokenInactivityTimeoutSeconds int `json:"accessTokenInactivityTimeoutSeconds" yaml:"accessTokenInactivityTimeoutSeconds"`
|
AccessTokenInactivityTimeout time.Duration `json:"accessTokenInactivityTimeout" yaml:"accessTokenInactivityTimeout"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type IdentityProvider struct {
|
type DynamicOptions map[string]interface{}
|
||||||
|
|
||||||
|
type IdentityProviderOptions struct {
|
||||||
// The provider name.
|
// The provider name.
|
||||||
Name string `json:"name" yaml:"name"`
|
Name string `json:"name" yaml:"name"`
|
||||||
|
|
||||||
@@ -96,8 +95,8 @@ type IdentityProvider struct {
|
|||||||
// The type of identify provider
|
// The type of identify provider
|
||||||
Type string `json:"type" yaml:"type"`
|
Type string `json:"type" yaml:"type"`
|
||||||
|
|
||||||
// Provider options
|
// The options of identify provider
|
||||||
Github *Github `json:"github" yaml:"github" `
|
Provider *DynamicOptions `json:"provider,omitempty" yaml:"provider,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
@@ -145,15 +144,15 @@ type Client struct {
|
|||||||
// If no restriction matches, then the scope is denied.
|
// If no restriction matches, then the scope is denied.
|
||||||
ScopeRestrictions []string `json:"scopeRestrictions,omitempty" yaml:"scopeRestrictions,omitempty"`
|
ScopeRestrictions []string `json:"scopeRestrictions,omitempty" yaml:"scopeRestrictions,omitempty"`
|
||||||
|
|
||||||
// AccessTokenMaxAgeSeconds overrides the default access token max age for tokens granted to this client.
|
// AccessTokenMaxAge overrides the default access token max age for tokens granted to this client.
|
||||||
AccessTokenMaxAgeSeconds *int `json:"accessTokenMaxAgeSeconds,omitempty" yaml:"accessTokenMaxAgeSeconds,omitempty"`
|
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.
|
// 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 {
|
for _, found := range o.Clients {
|
||||||
if found.Name == name {
|
if found.Name == name {
|
||||||
return found, nil
|
return found, nil
|
||||||
@@ -161,13 +160,13 @@ func (o *Options) GetOAuthClient(name string) (Client, error) {
|
|||||||
}
|
}
|
||||||
return Client{}, ErrorClientNotFound
|
return Client{}, ErrorClientNotFound
|
||||||
}
|
}
|
||||||
func (o *Options) GetIdentityProvider(name string) (IdentityProvider, error) {
|
func (o *Options) IdentityProviderOptions(name string) (IdentityProviderOptions, error) {
|
||||||
for _, found := range o.IdentityProviders {
|
for _, found := range o.IdentityProviders {
|
||||||
if found.Name == name {
|
if found.Name == name {
|
||||||
return found, nil
|
return found, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return IdentityProvider{}, ErrorClientNotFound
|
return IdentityProviderOptions{}, ErrorClientNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c Client) ResolveRedirectURL(expectURL string) (string, error) {
|
func (c Client) ResolveRedirectURL(expectURL string) (string, error) {
|
||||||
@@ -183,21 +182,11 @@ func (c Client) ResolveRedirectURL(expectURL string) (string, error) {
|
|||||||
return "", ErrorRedirectURLNotAllowed
|
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 {
|
func NewOptions() *Options {
|
||||||
return &Options{
|
return &Options{
|
||||||
IdentityProviders: make([]IdentityProvider, 0),
|
IdentityProviders: make([]IdentityProviderOptions, 0),
|
||||||
Clients: make([]Client, 0),
|
Clients: make([]Client, 0),
|
||||||
AccessTokenMaxAgeSeconds: 86400,
|
AccessTokenMaxAge: time.Hour * 24,
|
||||||
AccessTokenInactivityTimeoutSeconds: 0,
|
AccessTokenInactivityTimeout: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,10 +18,12 @@
|
|||||||
|
|
||||||
package token
|
package token
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
// Issuer issues token to user, tokens are required to perform mutating requests to resources
|
// Issuer issues token to user, tokens are required to perform mutating requests to resources
|
||||||
type Issuer interface {
|
type Issuer interface {
|
||||||
// IssueTo issues a token a User, return error if issuing process failed
|
// 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 verifies a token, and return a User if it's a valid token, otherwise return error
|
||||||
Verify(string) (User, error)
|
Verify(string) (User, error)
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ func (s *jwtTokenIssuer) Verify(tokenString string) (User, error) {
|
|||||||
return &iam.User{Name: clm.Username, UID: clm.UID}, nil
|
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{
|
clm := &Claims{
|
||||||
Username: user.GetName(),
|
Username: user.GetName(),
|
||||||
UID: user.GetUID(),
|
UID: user.GetUID(),
|
||||||
@@ -83,8 +83,8 @@ func (s *jwtTokenIssuer) IssueTo(user User, expiresInSecond int) (string, error)
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if expiresInSecond > 0 {
|
if expiresIn > 0 {
|
||||||
clm.ExpiresAt = clm.IssuedAt + int64(expiresInSecond)
|
clm.ExpiresAt = clm.IssuedAt + int64(expiresIn.Seconds())
|
||||||
}
|
}
|
||||||
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, clm)
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, clm)
|
||||||
@@ -95,7 +95,7 @@ func (s *jwtTokenIssuer) IssueTo(user User, expiresInSecond int) (string, error)
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
s.cache.Set(tokenCacheKey(tokenString), tokenString, time.Second*time.Duration(expiresInSecond))
|
s.cache.Set(tokenCacheKey(tokenString), tokenString, expiresIn)
|
||||||
|
|
||||||
return tokenString, nil
|
return tokenString, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v2"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider/github"
|
||||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
||||||
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
||||||
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
|
"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/s3"
|
||||||
"kubesphere.io/kubesphere/pkg/simple/client/servicemesh"
|
"kubesphere.io/kubesphere/pkg/simple/client/servicemesh"
|
||||||
"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
|
"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
|
||||||
"kubesphere.io/kubesphere/pkg/utils/reflectutils"
|
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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{
|
var conf = &Config{
|
||||||
MySQLOptions: &mysql.Options{
|
MySQLOptions: &mysql.Options{
|
||||||
Host: "10.68.96.5:3306",
|
Host: "10.68.96.5:3306",
|
||||||
@@ -110,36 +125,27 @@ func newTestConfig() *Config {
|
|||||||
JwtSecret: "xxxxxx",
|
JwtSecret: "xxxxxx",
|
||||||
MultipleLogin: false,
|
MultipleLogin: false,
|
||||||
OAuthOptions: &oauth.Options{
|
OAuthOptions: &oauth.Options{
|
||||||
IdentityProviders: []oauth.IdentityProvider{{
|
IdentityProviders: []oauth.IdentityProviderOptions{{
|
||||||
Name: "github",
|
Name: "github",
|
||||||
MappingMethod: "auto",
|
MappingMethod: "auto",
|
||||||
LoginRedirect: true,
|
LoginRedirect: true,
|
||||||
Type: oauth.IdentityProviderTypeGithub,
|
Type: "github",
|
||||||
Github: &oauth.Github{
|
Provider: githubOAuthProvider,
|
||||||
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"},
|
|
||||||
},
|
|
||||||
}},
|
}},
|
||||||
Clients: []oauth.Client{{
|
Clients: []oauth.Client{{
|
||||||
Name: "kubesphere-console-client",
|
Name: "kubesphere-console-client",
|
||||||
Secret: "xxxxxx-xxxxxx-xxxxxx",
|
Secret: "xxxxxx-xxxxxx-xxxxxx",
|
||||||
RespondWithChallenges: true,
|
RespondWithChallenges: true,
|
||||||
RedirectURIs: []string{"http://ks-console.kubesphere-system.svc/oauth/token/implicit"},
|
RedirectURIs: []string{"http://ks-console.kubesphere-system.svc/oauth/token/implicit"},
|
||||||
GrantMethod: oauth.GrantHandlerAuto,
|
GrantMethod: oauth.GrantHandlerAuto,
|
||||||
AccessTokenInactivityTimeoutSeconds: nil,
|
AccessTokenInactivityTimeout: nil,
|
||||||
}},
|
}},
|
||||||
AccessTokenMaxAgeSeconds: 86400,
|
AccessTokenMaxAge: time.Hour * 24,
|
||||||
AccessTokenInactivityTimeoutSeconds: 0,
|
AccessTokenInactivityTimeout: 0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
return conf
|
return conf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveTestConfig(t *testing.T, conf *Config) {
|
func saveTestConfig(t *testing.T, conf *Config) {
|
||||||
@@ -147,7 +153,6 @@ func saveTestConfig(t *testing.T, conf *Config) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("error marshal config. %v", err)
|
t.Fatalf("error marshal config. %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ioutil.WriteFile(fmt.Sprintf("%s.yaml", defaultConfigurationName), content, 0640)
|
err = ioutil.WriteFile(fmt.Sprintf("%s.yaml", defaultConfigurationName), content, 0640)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("error write configuration file, %v", err)
|
t.Fatalf("error write configuration file, %v", err)
|
||||||
@@ -169,7 +174,10 @@ func cleanTestConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestGet(t *testing.T) {
|
func TestGet(t *testing.T) {
|
||||||
conf := newTestConfig()
|
conf, err := newTestConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
saveTestConfig(t, conf)
|
saveTestConfig(t, conf)
|
||||||
defer cleanTestConfig(t)
|
defer cleanTestConfig(t)
|
||||||
|
|
||||||
@@ -178,8 +186,7 @@ func TestGet(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
cmp.Diff(conf, conf2)
|
if diff := cmp.Diff(conf, conf2); diff != "" {
|
||||||
if diff := reflectutils.Equal(conf, conf2); diff != nil {
|
|
||||||
t.Fatal(diff)
|
t.Fatal(diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import (
|
|||||||
"k8s.io/klog"
|
"k8s.io/klog"
|
||||||
"kubesphere.io/kubesphere/pkg/api"
|
"kubesphere.io/kubesphere/pkg/api"
|
||||||
"kubesphere.io/kubesphere/pkg/api/auth"
|
"kubesphere.io/kubesphere/pkg/api/auth"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"
|
||||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
||||||
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
||||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/token"
|
"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")
|
responseType := req.QueryParameter("response_type")
|
||||||
redirectURI := req.QueryParameter("redirect_uri")
|
redirectURI := req.QueryParameter("redirect_uri")
|
||||||
|
|
||||||
conf, err := h.options.OAuthOptions.GetOAuthClient(clientId)
|
conf, err := h.options.OAuthOptions.OAuthClient(clientId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err))
|
err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err))
|
||||||
@@ -105,10 +106,10 @@ func (h *oauthHandler) AuthorizeHandler(req *restful.Request, resp *restful.Resp
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
expiresIn := h.options.OAuthOptions.AccessTokenMaxAgeSeconds
|
expiresIn := h.options.OAuthOptions.AccessTokenMaxAge
|
||||||
|
|
||||||
if conf.AccessTokenMaxAgeSeconds != nil {
|
if conf.AccessTokenMaxAge != nil {
|
||||||
expiresIn = *conf.AccessTokenMaxAgeSeconds
|
expiresIn = *conf.AccessTokenMaxAge
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, err := h.issuer.IssueTo(user, expiresIn)
|
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)
|
redirectURL = fmt.Sprintf("%s#access_token=%s&token_type=Bearer", redirectURL, accessToken)
|
||||||
|
|
||||||
if expiresIn > 0 {
|
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")
|
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)
|
resp.WriteError(http.StatusUnauthorized, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
idP, err := h.options.OAuthOptions.GetIdentityProvider(name)
|
idP, err := h.options.OAuthOptions.IdentityProviderOptions(name)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err))
|
err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err))
|
||||||
resp.WriteError(http.StatusUnauthorized, err)
|
resp.WriteError(http.StatusUnauthorized, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
oauthIdentityProvider, err := idP.GetOAuth2IdentityProviderInstance()
|
oauthIdentityProvider, err := identityprovider.ResolveOAuthProvider(idP.Type, idP.Provider)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err := apierrors.NewUnauthorized(fmt.Sprintf("Unauthorized: %s", err))
|
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)
|
resp.WriteError(http.StatusUnauthorized, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
expiresIn := h.options.OAuthOptions.AccessTokenMaxAgeSeconds
|
expiresIn := h.options.OAuthOptions.AccessTokenMaxAge
|
||||||
|
|
||||||
accessToken, err := h.issuer.IssueTo(user, expiresIn)
|
accessToken, err := h.issuer.IssueTo(user, expiresIn)
|
||||||
|
|
||||||
@@ -181,7 +182,7 @@ func (h *oauthHandler) OAuthCallBackHandler(req *restful.Request, resp *restful.
|
|||||||
result := oauth.Token{
|
result := oauth.Token{
|
||||||
AccessToken: accessToken,
|
AccessToken: accessToken,
|
||||||
TokenType: "Bearer",
|
TokenType: "Bearer",
|
||||||
ExpiresIn: expiresIn,
|
ExpiresIn: int(expiresIn.Seconds()),
|
||||||
}
|
}
|
||||||
|
|
||||||
resp.WriteEntity(result)
|
resp.WriteEntity(result)
|
||||||
|
|||||||
@@ -23,12 +23,19 @@ import (
|
|||||||
restfulspec "github.com/emicklei/go-restful-openapi"
|
restfulspec "github.com/emicklei/go-restful-openapi"
|
||||||
"kubesphere.io/kubesphere/pkg/api"
|
"kubesphere.io/kubesphere/pkg/api"
|
||||||
"kubesphere.io/kubesphere/pkg/api/auth"
|
"kubesphere.io/kubesphere/pkg/api/auth"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
|
||||||
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
|
||||||
"kubesphere.io/kubesphere/pkg/apiserver/authentication/token"
|
"kubesphere.io/kubesphere/pkg/apiserver/authentication/token"
|
||||||
"kubesphere.io/kubesphere/pkg/constants"
|
"kubesphere.io/kubesphere/pkg/constants"
|
||||||
"net/http"
|
"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 <ks-apiserver>/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 <ks-apiserver>/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 {
|
func AddToContainer(c *restful.Container, issuer token.Issuer, options *authoptions.AuthenticationOptions) error {
|
||||||
ws := &restful.WebService{}
|
ws := &restful.WebService{}
|
||||||
ws.Path("/oauth").
|
ws.Path("/oauth").
|
||||||
@@ -48,12 +55,17 @@ func AddToContainer(c *restful.Container, issuer token.Issuer, options *authopti
|
|||||||
|
|
||||||
// Only support implicit grant flow
|
// Only support implicit grant flow
|
||||||
// https://tools.ietf.org/html/rfc6749#section-4.2
|
// 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").
|
ws.Route(ws.GET("/authorize").
|
||||||
|
Doc("All requests for OAuth tokens involve a request to <ks-apiserver>/oauth/authorize.").
|
||||||
To(handler.AuthorizeHandler))
|
To(handler.AuthorizeHandler))
|
||||||
//ws.Route(ws.POST("/token"))
|
//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}").
|
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)
|
c.Add(ws)
|
||||||
|
|
||||||
|
|||||||
@@ -16,30 +16,34 @@
|
|||||||
* /
|
* /
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package serverconfig
|
package v1alpha2
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/emicklei/go-restful"
|
"github.com/emicklei/go-restful"
|
||||||
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||||
apiserverconfig "kubesphere.io/kubesphere/pkg/apiserver/config"
|
apiserverconfig "kubesphere.io/kubesphere/pkg/apiserver/config"
|
||||||
|
"kubesphere.io/kubesphere/pkg/apiserver/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
func AddToContainer(c *restful.Container, config *apiserverconfig.Config) error {
|
const (
|
||||||
configs := &restful.WebService{}
|
GroupName = "config.kubesphere.io"
|
||||||
|
)
|
||||||
|
|
||||||
configs.Path("/server/configs").
|
var GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha2"}
|
||||||
Consumes(restful.MIME_JSON).
|
|
||||||
Produces(restful.MIME_JSON)
|
func AddToContainer(c *restful.Container, config *apiserverconfig.Config) error {
|
||||||
|
webservice := runtime.NewWebService(GroupVersion)
|
||||||
|
|
||||||
// information about the authorization server are published.
|
// 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)
|
response.WriteEntity(config.AuthenticationOptions.OAuthOptions)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// information about the server configuration
|
// 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())
|
response.WriteAsJson(config.ToMap())
|
||||||
}))
|
}))
|
||||||
|
|
||||||
c.Add(configs)
|
c.Add(webservice)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user