auth.go 3.0 KB

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