-
Notifications
You must be signed in to change notification settings - Fork 93
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add BasicAuth support into the example app
- Loading branch information
1 parent
8ef0ecb
commit a82f621
Showing
4 changed files
with
77 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package main | ||
|
||
import ( | ||
"flag" | ||
"net/http" | ||
) | ||
|
||
type basicAuthConfig struct { | ||
username string | ||
password string | ||
} | ||
|
||
func newBasicAuthConfigFromFlags() *basicAuthConfig { | ||
c := &basicAuthConfig{} | ||
flag.StringVar(&c.username, "basic-auth-username", "", "BasicAuth username") | ||
flag.StringVar(&c.password, "basic-auth-password", "", "BasicAuth password") | ||
return c | ||
} | ||
|
||
func (c *basicAuthConfig) isEnabled() bool { | ||
return c.username != "" || c.password != "" | ||
} | ||
|
||
func (c *basicAuthConfig) handle(handler http.Handler) http.Handler { | ||
if !c.isEnabled() { | ||
return handler | ||
} | ||
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
username, password, ok := r.BasicAuth() | ||
if ok && username == c.username && password == c.password { | ||
handler.ServeHTTP(w, r) | ||
return | ||
} | ||
|
||
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) | ||
http.Error(w, "Unauthorized", http.StatusUnauthorized) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters