本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.6KB

  1. package openidConnect
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/markbates/goth"
  6. "golang.org/x/oauth2"
  7. "strings"
  8. "time"
  9. )
  10. // Session stores data during the auth process with the OpenID Connect provider.
  11. type Session struct {
  12. AuthURL string
  13. AccessToken string
  14. RefreshToken string
  15. ExpiresAt time.Time
  16. IDToken string
  17. }
  18. // GetAuthURL will return the URL set by calling the `BeginAuth` function on the OpenID Connect provider.
  19. func (s Session) GetAuthURL() (string, error) {
  20. if s.AuthURL == "" {
  21. return "", errors.New("an AuthURL has not be set")
  22. }
  23. return s.AuthURL, nil
  24. }
  25. // Authorize the session with the OpenID Connect provider and return the access token to be stored for future use.
  26. func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
  27. p := provider.(*Provider)
  28. token, err := p.config.Exchange(oauth2.NoContext, params.Get("code"))
  29. if err != nil {
  30. return "", err
  31. }
  32. if !token.Valid() {
  33. return "", errors.New("Invalid token received from provider")
  34. }
  35. s.AccessToken = token.AccessToken
  36. s.RefreshToken = token.RefreshToken
  37. s.ExpiresAt = token.Expiry
  38. s.IDToken = token.Extra("id_token").(string)
  39. return token.AccessToken, err
  40. }
  41. // Marshal the session into a string
  42. func (s Session) Marshal() string {
  43. b, _ := json.Marshal(s)
  44. return string(b)
  45. }
  46. func (s Session) String() string {
  47. return s.Marshal()
  48. }
  49. // UnmarshalSession will unmarshal a JSON string into a session.
  50. func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
  51. sess := &Session{}
  52. err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
  53. return sess, err
  54. }
上海开阖软件有限公司 沪ICP备12045867号-1