auth.go 3.1 KB

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