auth.go 3.1 KB

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