Skip to content

Instantly share code, notes, and snippets.

@rohit20001221
Created April 27, 2025 12:56
Show Gist options
  • Select an option

  • Save rohit20001221/fd2872892a6774a5d0b808a8f5beda53 to your computer and use it in GitHub Desktop.

Select an option

Save rohit20001221/fd2872892a6774a5d0b808a8f5beda53 to your computer and use it in GitHub Desktop.
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