Created
April 27, 2025 12:56
-
-
Save rohit20001221/fd2872892a6774a5d0b808a8f5beda53 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package middlewares | |
| import ( | |
| "crypto/sha256" | |
| "crypto/subtle" | |
| "net/http" | |
| ) | |
| func NewBasicAuthMiddleware(h http.Handler) http.Handler { | |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| username, password, ok := r.BasicAuth() | |
| if ok { | |
| usernameHash := sha256.Sum256([]byte(username)) | |
| passwordHash := sha256.Sum256([]byte(password)) | |
| expectedUsernameHash := sha256.Sum256([]byte("[email protected]")) | |
| expectedPasswordHash := sha256.Sum256([]byte("admin@admin")) | |
| usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1) | |
| passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1) | |
| if usernameMatch && passwordMatch { | |
| h.ServeHTTP(w, r) | |
| return | |
| } | |
| } | |
| w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) | |
| http.Error(w, "Unauthorized", http.StatusUnauthorized) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment