-
-
Notifications
You must be signed in to change notification settings - Fork 161
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* WIP basic auth token * remove output.diff * implemented reviewed changes * clean up config.go
- Loading branch information
Showing
5 changed files
with
85 additions
and
9 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
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,40 @@ | ||
package middleware | ||
|
||
import ( | ||
"crypto/subtle" | ||
"fmt" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
// TokenAuth implements a similar middleware handler like go-chi's BasicAuth middleware but for bearer tokens | ||
func TokenAuth(realm string, token string) func(next http.Handler) http.Handler { | ||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
authHeader := strings.Split(r.Header.Get("Authorization"), " ") | ||
if len(authHeader) < 2 { | ||
tokenAuthFailed(w, realm) | ||
return | ||
} | ||
|
||
bearer := authHeader[1] | ||
if bearer == "" { | ||
tokenAuthFailed(w, realm) | ||
return | ||
} | ||
|
||
if subtle.ConstantTimeCompare([]byte(bearer), []byte(token)) != 1 { | ||
tokenAuthFailed(w, realm) | ||
return | ||
} | ||
|
||
next.ServeHTTP(w, r) | ||
|
||
}) | ||
} | ||
} | ||
|
||
func tokenAuthFailed(w http.ResponseWriter, realm string) { | ||
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Bearer realm="%s"`, realm)) | ||
w.WriteHeader(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