auth.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "strconv"
  9. )
  10. const AuthUserKey = "user"
  11. type (
  12. Accounts map[string]string
  13. authPair struct {
  14. Value string
  15. User string
  16. }
  17. authPairs []authPair
  18. )
  19. func (a authPairs) searchCredential(authValue string) (string, bool) {
  20. if len(authValue) == 0 {
  21. return "", false
  22. }
  23. for _, pair := range a {
  24. if pair.Value == authValue {
  25. return pair.User, true
  26. }
  27. }
  28. return "", false
  29. }
  30. // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
  31. // the key is the user name and the value is the password, as well as the name of the Realm.
  32. // If the realm is empty, "Authorization Required" will be used by default.
  33. // (see http://tools.ietf.org/html/rfc2617#section-1.2)
  34. func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
  35. if realm == "" {
  36. realm = "Authorization Required"
  37. }
  38. realm = "Basic realm=" + strconv.Quote(realm)
  39. pairs := processAccounts(accounts)
  40. return func(c *Context) {
  41. // Search user in the slice of allowed credentials
  42. user, found := pairs.searchCredential(c.Request.Header.Get("Authorization"))
  43. if !found {
  44. // Credentials doesn't match, we return 401 and abort handlers chain.
  45. c.Header("WWW-Authenticate", realm)
  46. c.AbortWithStatus(401)
  47. } else {
  48. // The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using
  49. // c.MustGet(gin.AuthUserKey)
  50. c.Set(AuthUserKey, user)
  51. }
  52. }
  53. }
  54. // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
  55. // the key is the user name and the value is the password.
  56. func BasicAuth(accounts Accounts) HandlerFunc {
  57. return BasicAuthForRealm(accounts, "")
  58. }
  59. func processAccounts(accounts Accounts) authPairs {
  60. if len(accounts) == 0 {
  61. panic("Empty list of authorized credentials")
  62. }
  63. pairs := make(authPairs, 0, len(accounts))
  64. for user, password := range accounts {
  65. if len(user) == 0 {
  66. panic("User can not be empty")
  67. }
  68. value := authorizationHeader(user, password)
  69. pairs = append(pairs, authPair{
  70. Value: value,
  71. User: user,
  72. })
  73. }
  74. return pairs
  75. }
  76. func authorizationHeader(user, password string) string {
  77. base := user + ":" + password
  78. return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  79. }
  80. func secureCompare(given, actual string) bool {
  81. if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
  82. return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
  83. }
  84. /* Securely compare actual to itself to keep constant time, but always return false */
  85. return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
  86. }