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.
14 // AuthUserKey is the cookie name for user credential in basic auth.
15 const AuthUserKey = "user"
17 // Accounts defines a key/value for user/pass list of authorized logins.
18 type Accounts map[string]string
20 type authPair struct {
25 type authPairs []authPair
27 func (a authPairs) searchCredential(authValue string) (string, bool) {
31 for _, pair := range a {
32 if pair.value == authValue {
33 return pair.user, true
39 // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
40 // the key is the user name and the value is the password, as well as the name of the Realm.
41 // If the realm is empty, "Authorization Required" will be used by default.
42 // (see http://tools.ietf.org/html/rfc2617#section-1.2)
43 func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
45 realm = "Authorization Required"
47 realm = "Basic realm=" + strconv.Quote(realm)
48 pairs := processAccounts(accounts)
49 return func(c *Context) {
50 // Search user in the slice of allowed credentials
51 user, found := pairs.searchCredential(c.requestHeader("Authorization"))
53 // Credentials doesn't match, we return 401 and abort handlers chain.
54 c.Header("WWW-Authenticate", realm)
55 c.AbortWithStatus(http.StatusUnauthorized)
59 // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using
60 // c.MustGet(gin.AuthUserKey).
61 c.Set(AuthUserKey, user)
65 // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
66 // the key is the user name and the value is the password.
67 func BasicAuth(accounts Accounts) HandlerFunc {
68 return BasicAuthForRealm(accounts, "")
71 func processAccounts(accounts Accounts) authPairs {
72 assert1(len(accounts) > 0, "Empty list of authorized credentials")
73 pairs := make(authPairs, 0, len(accounts))
74 for user, password := range accounts {
75 assert1(user != "", "User can not be empty")
76 value := authorizationHeader(user, password)
77 pairs = append(pairs, authPair{
85 func authorizationHeader(user, password string) string {
86 base := user + ":" + password
87 return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
90 func secureCompare(given, actual string) bool {
91 if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
92 return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
94 // Securely compare actual to itself to keep constant time, but always return false.
95 return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false