auth.go 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // AuthUserKey is the cookie name for user credential in basic auth.
  11. const AuthUserKey = "user"
  12. // Accounts defines a key/value for user/pass list of authorized logins.
  13. type Accounts map[string]string
  14. type authPair struct {
  15. Value string
  16. User string
  17. }
  18. type authPairs []authPair
  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. return
  48. }
  49. // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using
  50. // c.MustGet(gin.AuthUserKey).
  51. c.Set(AuthUserKey, user)
  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. assert1(len(accounts) > 0, "Empty list of authorized credentials")
  61. pairs := make(authPairs, 0, len(accounts))
  62. for user, password := range accounts {
  63. assert1(len(user) > 0, "User can not be empty")
  64. value := authorizationHeader(user, password)
  65. pairs = append(pairs, authPair{
  66. Value: value,
  67. User: user,
  68. })
  69. }
  70. return pairs
  71. }
  72. func authorizationHeader(user, password string) string {
  73. base := user + ":" + password
  74. return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  75. }
  76. func secureCompare(given, actual string) bool {
  77. if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
  78. return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
  79. }
  80. // Securely compare actual to itself to keep constant time, but always return false.
  81. return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
  82. }