summaryrefslogtreecommitdiffhomepage
path: root/middleware/basicauth/basicauth.go
blob: de29b8d9a64560a611d6d35ebe5b413e9c7dcab2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Package basicauth implements HTTP Basic Authentication.
package basicauth

import (
	"net/http"

	"github.com/mholt/caddy/middleware"
)

// BasicAuth is middleware to protect resources with a username and password.
// Note that HTTP Basic Authentication is not secure by itself and should
// not be used to protect important assets without HTTPS. Even then, the
// security of HTTP Basic Auth is disputed. Use discretion when deciding
// what to protect with BasicAuth.
type BasicAuth struct {
	Next  middleware.Handler
	Rules []Rule
}

// ServeHTTP implements the middleware.Handler interface.
func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range a.Rules {
		for _, res := range rule.Resources {
			if !middleware.Path(r.URL.Path).Matches(res) {
				continue
			}

			// Path matches; parse auth header
			username, password, ok := r.BasicAuth()

			// Check credentials
			if !ok || username != rule.Username || password != rule.Password {
				w.Header().Set("WWW-Authenticate", "Basic")
				return http.StatusUnauthorized, nil
			}

			// "It's an older code, sir, but it checks out. I was about to clear them."
			return a.Next.ServeHTTP(w, r)
		}
	}

	// Pass-thru when no paths match
	return a.Next.ServeHTTP(w, r)
}

// Rule represents a BasicAuth rule. A username and password
// combination protect the associated resources, which are
// file or directory paths.
type Rule struct {
	Username  string
	Password  string
	Resources []string
}