idp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 sp
  15. import (
  16. "net/url"
  17. "yunion.io/x/pkg/errors"
  18. "yunion.io/x/pkg/util/samlutils"
  19. "yunion.io/x/onecloud/pkg/httperrors"
  20. )
  21. type SSAMLIdentityProvider struct {
  22. entityId string
  23. redirectSsoUrl string
  24. }
  25. func NewSAMLIdp(entityId, redirectSsoUrl string) *SSAMLIdentityProvider {
  26. return &SSAMLIdentityProvider{
  27. entityId: entityId,
  28. redirectSsoUrl: redirectSsoUrl,
  29. }
  30. }
  31. func NewSAMLIdpFromDescriptor(desc samlutils.EntityDescriptor) (*SSAMLIdentityProvider, error) {
  32. entityId := desc.EntityId
  33. if desc.IDPSSODescriptor == nil {
  34. return nil, errors.Wrap(httperrors.ErrInputParameter, "missing IDPSSODescriptor")
  35. }
  36. redirectSsoUrl := findSSOUrl(desc, samlutils.BINDING_HTTP_REDIRECT)
  37. return NewSAMLIdp(entityId, redirectSsoUrl), nil
  38. }
  39. func (idp *SSAMLIdentityProvider) GetEntityId() string {
  40. return idp.entityId
  41. }
  42. func findSSOUrl(desc samlutils.EntityDescriptor, binding string) string {
  43. for _, v := range desc.IDPSSODescriptor.SingleSignOnServices {
  44. if v.Binding == binding {
  45. return v.Location
  46. }
  47. }
  48. return ""
  49. }
  50. func (idp *SSAMLIdentityProvider) getRedirectSSOUrl() string {
  51. return idp.redirectSsoUrl
  52. }
  53. func (idp *SSAMLIdentityProvider) IsValid() error {
  54. if len(idp.GetEntityId()) == 0 {
  55. return errors.Wrap(httperrors.ErrInputParameter, "empty EntityID")
  56. }
  57. ssoUrlStr := idp.getRedirectSSOUrl()
  58. if len(ssoUrlStr) == 0 {
  59. return errors.Wrap(httperrors.ErrInvalidFormat, "empty redirect SSO URL")
  60. }
  61. _, err := url.Parse(ssoUrlStr)
  62. if err != nil {
  63. return errors.Wrapf(err, "invalid redirect SSO URL: %s", ssoUrlStr)
  64. }
  65. return nil
  66. }