Signed-off-by: hongming <talonwan@yunify.com>
This commit is contained in:
hongming
2020-03-26 18:42:01 +08:00
parent 9b9d4021ec
commit 96a1d3825e
10 changed files with 187 additions and 93 deletions

View File

@@ -1,157 +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 oauth
import (
"context"
"encoding/json"
"golang.org/x/oauth2"
"io/ioutil"
"k8s.io/apiserver/pkg/authentication/user"
"time"
)
const (
UserInfoURL = "https://api.github.com/user"
)
type Github struct {
// ClientID is the application's ID.
ClientID string `json:"clientID" yaml:"clientID"`
// ClientSecret is the application's secret.
ClientSecret string `json:"-" yaml:"clientSecret"`
// Endpoint contains the resource server's token endpoint
// URLs. These are constants specific to each server and are
// often available via site-specific packages, such as
// google.Endpoint or github.Endpoint.
Endpoint Endpoint `json:"endpoint" yaml:"endpoint"`
// RedirectURL is the URL to redirect users going through
// the OAuth flow, after the resource owner's URLs.
RedirectURL string `json:"redirectURL" yaml:"redirectURL"`
// Scope specifies optional requested permissions.
Scopes []string `json:"scopes" yaml:"scopes"`
}
// Endpoint represents an OAuth 2.0 provider's authorization and token
// endpoint URLs.
type Endpoint struct {
AuthURL string `json:"authURL" yaml:"authURL"`
TokenURL string `json:"tokenURL" yaml:"tokenURL"`
}
type GithubIdentity struct {
Login string `json:"login"`
ID string `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
Name string `json:"name"`
Company string `json:"company"`
Blog string `json:"blog"`
Location string `json:"location"`
Email string `json:"email"`
Hireable bool `json:"hireable"`
Bio string `json:"bio"`
PublicRepos int `json:"public_repos"`
PublicGists int `json:"public_gists"`
Followers int `json:"followers"`
Following int `json:"following"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PrivateGists int `json:"private_gists"`
TotalPrivateRepos int `json:"total_private_repos"`
OwnedPrivateRepos int `json:"owned_private_repos"`
DiskUsage int `json:"disk_usage"`
Collaborators int `json:"collaborators"`
}
func (g GithubIdentity) GetName() string {
return g.Login
}
func (g GithubIdentity) GetUID() string {
return g.ID
}
func (g GithubIdentity) GetGroups() []string {
return nil
}
func (g GithubIdentity) GetExtra() map[string][]string {
return nil
}
func (g *Github) IdentityExchange(code string) (user.Info, error) {
config := oauth2.Config{
ClientID: g.ClientID,
ClientSecret: g.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: g.Endpoint.AuthURL,
TokenURL: g.Endpoint.TokenURL,
AuthStyle: oauth2.AuthStyleAutoDetect,
},
RedirectURL: g.RedirectURL,
Scopes: g.Scopes,
}
token, err := config.Exchange(context.Background(), code)
if err != nil {
return nil, err
}
resp, err := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(token)).Get(UserInfoURL)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
var githubIdentity GithubIdentity
err = json.Unmarshal(data, &githubIdentity)
if err != nil {
return nil, err
}
return githubIdentity, nil
}

View File

@@ -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,
}
}