auth.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "crypto/subtle"
  7. "encoding/base64"
  8. "errors"
  9. "fmt"
  10. "sort"
  11. )
  12. const (
  13. AuthUserKey = "user"
  14. )
  15. type (
  16. Accounts map[string]string
  17. authPair struct {
  18. Value string
  19. User string
  20. }
  21. authPairs []authPair
  22. )
  23. func (a authPairs) Len() int { return len(a) }
  24. func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  25. func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }
  26. // Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where
  27. // the key is the user name and the value is the password, as well as the name of the Realm
  28. // (see http://tools.ietf.org/html/rfc2617#section-1.2)
  29. func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
  30. pairs, err := processAccounts(accounts)
  31. if err != nil {
  32. panic(err)
  33. }
  34. return func(c *Context) {
  35. // Search user in the slice of allowed credentials
  36. user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))
  37. if !ok {
  38. // Credentials doesn't match, we return 401 Unauthorized and abort request.
  39. if realm == "" {
  40. realm = "Authorization Required"
  41. }
  42. c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))
  43. c.Fail(401, errors.New("Unauthorized"))
  44. } else {
  45. // user is allowed, set UserId to key "user" in this context, the userId can be read later using
  46. // c.Get(gin.AuthUserKey)
  47. c.Set(AuthUserKey, user)
  48. }
  49. }
  50. }
  51. // Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
  52. // the key is the user name and the value is the password.
  53. func BasicAuth(accounts Accounts) HandlerFunc {
  54. return BasicAuthForRealm(accounts, "")
  55. }
  56. func processAccounts(accounts Accounts) (authPairs, error) {
  57. if len(accounts) == 0 {
  58. return nil, errors.New("Empty list of authorized credentials")
  59. }
  60. pairs := make(authPairs, 0, len(accounts))
  61. for user, password := range accounts {
  62. if len(user) == 0 {
  63. return nil, errors.New("User can not be empty")
  64. }
  65. base := user + ":" + password
  66. value := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  67. pairs = append(pairs, authPair{
  68. Value: value,
  69. User: user,
  70. })
  71. }
  72. // We have to sort the credentials in order to use bsearch later.
  73. sort.Sort(pairs)
  74. return pairs, nil
  75. }
  76. func searchCredential(pairs authPairs, auth string) (string, bool) {
  77. if len(auth) == 0 {
  78. return "", false
  79. }
  80. // Search user in the slice of allowed credentials
  81. r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Value >= auth })
  82. if r < len(pairs) && secureCompare(pairs[r].Value, auth) {
  83. return pairs[r].User, true
  84. } else {
  85. return "", false
  86. }
  87. }
  88. func secureCompare(given, actual string) bool {
  89. if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
  90. return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
  91. } else {
  92. /* Securely compare actual to itself to keep constant time, but always return false */
  93. return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
  94. }
  95. }