umbracle/ethgo

Accessing Nodes with Authorization

Closed this issue · 9 comments

At the moment I can't see any method of passing in Basic Auth for bare metal nodes. At Blockdaemon some of our nodes require authentication to be used which requires tokens to be passed in as headers on HTTP requests. I've written a really basic method to amend it and retain all the original functionality of the jsonrpc.Client type. Where the headers are passed down and ignored where possible. I'm happy to share this code if required or if you have your own implementation/pattern you'd like to use I'm happy to collaborate on it?

Below are the key changes to these methods/structs.

func NewClient(addr string) (*Client, error) {
	NewClientWithHeaders(addr, nil)
}

func NewClientWithHeaders(addr string, headers map[string]string) (*Client, error)

func newHTTP(addr string, headers map[string]string) *HTTP {
	return &HTTP{
		addr:    addr,
		client:  &fasthttp.Client{},
		headers: headers,
	}
}

Hi, do you need also for websocket? I was thinking something on this line:

func NewTransport(url string, headers map[string]string) (Transport, error) {
    ...
} 
type Config struct {
   headers map[string]string
}

type ConfigOption func(*Config)

func WithHeaders(headers map[string]string) ConfigOption {
	return func(c *Config) {
                for k, v := range headers {
                     c.headers[k] = v
                }
	}
}

func NewClient(addr string, opts ...ConfigOption) (*Client, error) {
    config := &Config{headers: map[string]string}
    for _, opt := range opts {
        opt(config)
    }
    transport.NewTransport(config)
}

I've not got a use case for the websocket one right now but yeah it probably makes sense to implement it at the same time.

Yeah what's written above looks fine, reduces the number of client options. Do you need a new method for NewTransport or are you going to adjust the signature to include (...Config)?

My bad, NewTransport now would be:

transport.NewTransport(addr, config.headers)

We can iterate more on top of this if there are more fields in Config but for now it is good.

Yeah I just had this, but yeah it makes sense to go with just the headers for now and add further config as when the need arises

        req.SetRequestURI(h.addr)
	req.Header.SetMethod("POST")
	req.Header.SetContentType("application/json")
	for k, v := range h.headers {
		req.Header.Add(k, v)
	}
	req.SetBody(raw)

Nice, do you want to do the PR?

Yep can do I'll just write the amendments in and submit the PR

Am I submitting this work to branch in this repo and if so do I need further access to be able to submit to branches?

You can create your changes in a fork and then PR your fork. You do not need any access to do that.

Fixed by #140