Add basic http auth to rpc server.

This commit is contained in:
John C. Vernaleo 2013-10-01 16:43:45 -04:00
parent ea256aeb5a
commit 73f08e72a2

View file

@ -5,7 +5,9 @@
package main package main
import ( import (
"encoding/base64"
"encoding/json" "encoding/json"
"fmt"
"github.com/conformal/btcchain" "github.com/conformal/btcchain"
"github.com/conformal/btcjson" "github.com/conformal/btcjson"
"github.com/conformal/btcscript" "github.com/conformal/btcscript"
@ -40,7 +42,14 @@ func (s *rpcServer) Start() {
log.Trace("[RPCS] Starting RPC server") log.Trace("[RPCS] Starting RPC server")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 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{} httpServer := &http.Server{}
for _, listener := range s.listeners { for _, listener := range s.listeners {
@ -108,6 +117,11 @@ func newRPCServer(s *server) (*rpcServer, error) {
return &rpc, err 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 // jsonRPCRead is the main function that handles reading messages, getting
// the data the message requests, and writing the reply. // the data the message requests, and writing the reply.
func jsonRPCRead(w http.ResponseWriter, r *http.Request, s *rpcServer) { func jsonRPCRead(w http.ResponseWriter, r *http.Request, s *rpcServer) {