From 73f08e72a258b7d94ccb6319020df424d02b46a5 Mon Sep 17 00:00:00 2001 From: "John C. Vernaleo" Date: Tue, 1 Oct 2013 16:43:45 -0400 Subject: [PATCH] Add basic http auth to rpc server. --- rpcserver.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/rpcserver.go b/rpcserver.go index 5bf44052..f89ad80f 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -5,7 +5,9 @@ package main import ( + "encoding/base64" "encoding/json" + "fmt" "github.com/conformal/btcchain" "github.com/conformal/btcjson" "github.com/conformal/btcscript" @@ -40,7 +42,14 @@ func (s *rpcServer) Start() { log.Trace("[RPCS] Starting RPC server") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - jsonRPCRead(w, r, s) + login := s.username + ":" + s.password + auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login)) + if r.Header["Authorization"][0] == auth { + jsonRPCRead(w, r, s) + } else { + log.Warnf("[RPCS] Auth failure.") + jsonAuthFail(w, r, s) + } }) httpServer := &http.Server{} for _, listener := range s.listeners { @@ -108,6 +117,11 @@ func newRPCServer(s *server) (*rpcServer, error) { return &rpc, err } +// jsonAuthFail sends a message back to the client if the http auth is rejected. +func jsonAuthFail(w http.ResponseWriter, r *http.Request, s *rpcServer) { + fmt.Fprint(w, "401 Unauthorized.\n") +} + // jsonRPCRead is the main function that handles reading messages, getting // the data the message requests, and writing the reply. func jsonRPCRead(w http.ResponseWriter, r *http.Request, s *rpcServer) {