bingoiam.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package bingoiam
  15. import (
  16. "context"
  17. "encoding/base64"
  18. "fmt"
  19. "net/http"
  20. "strings"
  21. "yunion.io/x/jsonutils"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/httputils"
  24. "yunion.io/x/onecloud/pkg/apis/identity"
  25. "yunion.io/x/onecloud/pkg/keystone/driver/oauth2"
  26. "yunion.io/x/onecloud/pkg/keystone/models"
  27. )
  28. type SBingoIAMOAuth2Driver struct {
  29. oauth2.SOAuth2BaseDriver
  30. idp *models.SIdentityProvider
  31. accessToken string
  32. domains map[string]*models.SDomain
  33. projects map[string]*models.SProject
  34. }
  35. func NewBingoIAMOAuth2Driver(appId string, secret string) oauth2.IOAuth2Driver {
  36. drv := &SBingoIAMOAuth2Driver{
  37. domains: map[string]*models.SDomain{},
  38. projects: map[string]*models.SProject{},
  39. SOAuth2BaseDriver: oauth2.SOAuth2BaseDriver{
  40. AppId: appId,
  41. Secret: secret,
  42. },
  43. }
  44. return drv
  45. }
  46. func (drv *SBingoIAMOAuth2Driver) getIAMEndpoint(ctx context.Context) string {
  47. endpoint := ""
  48. if config, isOk := ctx.Value("config").(identity.TConfigs); isOk {
  49. endpoint = strings.Trim(config["oauth2"]["iam_endpoint"].String(), `"`)
  50. }
  51. return endpoint
  52. }
  53. func (drv *SBingoIAMOAuth2Driver) getIAMApiEndpoint(ctx context.Context) string {
  54. endpoint := ""
  55. if config, isOk := ctx.Value("config").(identity.TConfigs); isOk {
  56. endpoint = strings.Trim(config["oauth2"]["iam_api_endpoint"].String(), `"`)
  57. }
  58. return endpoint
  59. }
  60. func (drv *SBingoIAMOAuth2Driver) GetSsoRedirectUri(ctx context.Context, callbackUrl, state string) (string, error) {
  61. req := map[string]string{
  62. "client_id": drv.AppId,
  63. "redirect_uri": callbackUrl,
  64. "response_type": "code id_token",
  65. "scope": "openid",
  66. "state": state,
  67. }
  68. authUrl := drv.getIAMEndpoint(ctx)
  69. urlStr := fmt.Sprintf("%s/oauth2/authorize?%s", authUrl, jsonutils.Marshal(req).QueryString())
  70. return urlStr, nil
  71. }
  72. func (drv *SBingoIAMOAuth2Driver) Authenticate(ctx context.Context, code string) (map[string][]string, error) {
  73. accessToken, err := drv.fetchAccessToken(ctx, code)
  74. if err != nil {
  75. return nil, errors.Wrap(err, "fetch bingo iam accessToken")
  76. }
  77. userInfo, err := drv.fetchUserInfo(ctx, accessToken)
  78. if err != nil {
  79. return nil, errors.Wrap(err, "fetch bingo iam userInfo")
  80. }
  81. attrs := make(map[string][]string)
  82. attrs["name"] = []string{fmt.Sprintf("%s", userInfo["preferred_username"])}
  83. attrs["display_name"] = []string{fmt.Sprintf("%s", userInfo["name"])}
  84. attrs["user_id"] = []string{fmt.Sprintf("%s", userInfo["sub"])}
  85. attrs["name_en"] = []string{fmt.Sprintf("%s", userInfo["preferred_username"])}
  86. attrs["email"] = []string{fmt.Sprintf("%s", userInfo["email"])}
  87. attrs["org_id"] = []string{fmt.Sprintf("%s", userInfo["org_id"])}
  88. attrs["mobile"] = []string{fmt.Sprintf("%s", userInfo["phone_number"])}
  89. attrs["tenant_id"] = []string{fmt.Sprintf("%s", userInfo["tenant_id"])}
  90. attrs["tenant_name"] = []string{fmt.Sprintf("%s", userInfo["tenant_name"])}
  91. return attrs, nil
  92. }
  93. func (drv *SBingoIAMOAuth2Driver) Sync(ctx context.Context, idpId string) error {
  94. var err error
  95. drv.idp, err = models.IdentityProviderManager.FetchIdentityProviderById(idpId)
  96. if err != nil {
  97. return err
  98. }
  99. //err = drv.syncTenants(ctx, drv.idp)
  100. //if err != nil {
  101. // return err
  102. //}
  103. //err = drv.syncProjects(ctx, drv.idp)
  104. //if err != nil {
  105. // return err
  106. //}
  107. //err = drv.syncUsers(ctx, drv.idp)
  108. //if err != nil {
  109. // return err
  110. //}
  111. return nil
  112. }
  113. func (drv *SBingoIAMOAuth2Driver) getAccessToken(ctx context.Context) (string, error) {
  114. authUrl := drv.getIAMEndpoint(ctx)
  115. authUrl = fmt.Sprintf("%s/oauth2/token?grant_type=client_credentials", authUrl)
  116. headers := http.Header{}
  117. headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", drv.AppId, drv.Secret))))
  118. httpclient := httputils.GetDefaultClient()
  119. _, resp, err := httputils.JSONRequest(httpclient, ctx, httputils.POST, authUrl, headers, nil, true)
  120. if err != nil {
  121. return "", err
  122. }
  123. var data map[string]interface{}
  124. err = resp.Unmarshal(&data)
  125. if err != nil {
  126. return "", err
  127. }
  128. drv.accessToken = data["access_token"].(string)
  129. return drv.accessToken, nil
  130. }
  131. func (drv *SBingoIAMOAuth2Driver) fetchAccessToken(ctx context.Context, code string) (string, error) {
  132. authUrl := drv.getIAMEndpoint(ctx)
  133. authUrl = fmt.Sprintf("%s/oauth2/token?grant_type=authorization_code&code=%s", authUrl, code)
  134. headers := http.Header{}
  135. headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", drv.AppId, drv.Secret))))
  136. httpclient := httputils.GetDefaultClient()
  137. _, resp, err := httputils.JSONRequest(httpclient, ctx, httputils.POST, authUrl, headers, nil, true)
  138. if err != nil {
  139. return "", err
  140. }
  141. var data map[string]interface{}
  142. err = resp.Unmarshal(&data)
  143. if err != nil {
  144. return "", err
  145. }
  146. return data["access_token"].(string), nil
  147. }
  148. func (drv *SBingoIAMOAuth2Driver) fetchUserInfo(ctx context.Context, accessToken string) (map[string]interface{}, error) {
  149. authUrl := drv.getIAMEndpoint(ctx)
  150. authUrl = fmt.Sprintf("%s/oauth2/userinfo?access_token=%s", authUrl, accessToken)
  151. headers := http.Header{}
  152. headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", drv.AppId, drv.Secret))))
  153. httpclient := httputils.GetDefaultClient()
  154. _, resp, err := httputils.JSONRequest(httpclient, ctx, httputils.GET, authUrl, headers, nil, true)
  155. if err != nil {
  156. return nil, err
  157. }
  158. var data map[string]interface{}
  159. err = resp.Unmarshal(&data)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return data, nil
  164. }