本站源代码
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.

88 lines
2.3KB

  1. package openid
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "sync"
  7. "time"
  8. )
  9. var maxNonceAge = flag.Duration("openid-max-nonce-age",
  10. 60*time.Second,
  11. "Maximum accepted age for openid nonces. The bigger, the more"+
  12. "memory is needed to store used nonces.")
  13. type NonceStore interface {
  14. // Returns nil if accepted, an error otherwise.
  15. Accept(endpoint, nonce string) error
  16. }
  17. type Nonce struct {
  18. T time.Time
  19. S string
  20. }
  21. type SimpleNonceStore struct {
  22. store map[string][]*Nonce
  23. mutex *sync.Mutex
  24. }
  25. func NewSimpleNonceStore() *SimpleNonceStore {
  26. return &SimpleNonceStore{store: map[string][]*Nonce{}, mutex: &sync.Mutex{}}
  27. }
  28. func (d *SimpleNonceStore) Accept(endpoint, nonce string) error {
  29. // Value: A string 255 characters or less in length, that MUST be
  30. // unique to this particular successful authentication response.
  31. if len(nonce) < 20 || len(nonce) > 256 {
  32. return errors.New("Invalid nonce")
  33. }
  34. // The nonce MUST start with the current time on the server, and MAY
  35. // contain additional ASCII characters in the range 33-126 inclusive
  36. // (printable non-whitespace characters), as necessary to make each
  37. // response unique. The date and time MUST be formatted as specified in
  38. // section 5.6 of [RFC3339], with the following restrictions:
  39. // All times must be in the UTC timezone, indicated with a "Z". No
  40. // fractional seconds are allowed For example:
  41. // 2005-05-15T17:11:51ZUNIQUE
  42. ts, err := time.Parse(time.RFC3339, nonce[0:20])
  43. if err != nil {
  44. return err
  45. }
  46. now := time.Now()
  47. diff := now.Sub(ts)
  48. if diff > *maxNonceAge {
  49. return fmt.Errorf("Nonce too old: %ds", diff.Seconds())
  50. }
  51. s := nonce[20:]
  52. // Meh.. now we have to use a mutex, to protect that map from
  53. // concurrent access. Could put a go routine in charge of it
  54. // though.
  55. d.mutex.Lock()
  56. defer d.mutex.Unlock()
  57. if nonces, hasOp := d.store[endpoint]; hasOp {
  58. // Delete old nonces while we are at it.
  59. newNonces := []*Nonce{{ts, s}}
  60. for _, n := range nonces {
  61. if n.T == ts && n.S == s {
  62. // If return early, just ignore the filtered list
  63. // we have been building so far...
  64. return errors.New("Nonce already used")
  65. }
  66. if now.Sub(n.T) < *maxNonceAge {
  67. newNonces = append(newNonces, n)
  68. }
  69. }
  70. d.store[endpoint] = newNonces
  71. } else {
  72. d.store[endpoint] = []*Nonce{{ts, s}}
  73. }
  74. return nil
  75. }
上海开阖软件有限公司 沪ICP备12045867号-1