@@ -8,13 +8,86 @@ import (
8
8
"net/http"
9
9
"regexp"
10
10
"strings"
11
+ "time"
11
12
12
13
"github.com/libp2p/go-libp2p"
14
+ "github.com/libp2p/go-libp2p/core/crypto"
13
15
"github.com/libp2p/go-libp2p/core/peer"
14
16
libp2phttp "github.com/libp2p/go-libp2p/p2p/http"
17
+ httpauth "github.com/libp2p/go-libp2p/p2p/http/auth"
15
18
ma "github.com/multiformats/go-multiaddr"
16
19
)
17
20
21
+ func ExampleHost_authenticatedHTTP () {
22
+ clientKey , _ , err := crypto .GenerateKeyPair (crypto .Ed25519 , 0 )
23
+ if err != nil {
24
+ log .Fatal (err )
25
+ }
26
+ client := libp2phttp.Host {
27
+ ClientPeerIDAuth : & httpauth.ClientPeerIDAuth {
28
+ TokenTTL : time .Hour ,
29
+ PrivKey : clientKey ,
30
+ },
31
+ }
32
+
33
+ serverKey , _ , err := crypto .GenerateKeyPair (crypto .Ed25519 , 0 )
34
+ if err != nil {
35
+ log .Fatal (err )
36
+ }
37
+ server := libp2phttp.Host {
38
+ ServerPeerIDAuth : & httpauth.ServerPeerIDAuth {
39
+ PrivKey : serverKey ,
40
+ // No TLS for this example. In practice you want to use TLS.
41
+ NoTLS : true ,
42
+ ValidHostnameFn : func (hostname string ) bool {
43
+ return strings .HasPrefix (hostname , "127.0.0.1" )
44
+ },
45
+ TokenTTL : time .Hour ,
46
+ },
47
+ // No TLS for this example. In practice you want to use TLS.
48
+ InsecureAllowHTTP : true ,
49
+ ListenAddrs : []ma.Multiaddr {ma .StringCast ("/ip4/127.0.0.1/tcp/0/http" )},
50
+ }
51
+
52
+ observedClientID := ""
53
+ server .SetHTTPHandler ("/echo-id" , http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
54
+ observedClientID = libp2phttp .ClientPeerID (r ).String ()
55
+ w .WriteHeader (http .StatusOK )
56
+ }))
57
+
58
+ go server .Serve ()
59
+ defer server .Close ()
60
+
61
+ expectedServerID , err := peer .IDFromPrivateKey (serverKey )
62
+ if err != nil {
63
+ log .Fatal (err )
64
+ }
65
+
66
+ httpClient := http.Client {Transport : & client }
67
+ url := fmt .Sprintf ("multiaddr:%s/p2p/%s/http-path/echo-id" , server .Addrs ()[0 ], expectedServerID )
68
+ resp , err := httpClient .Get (url )
69
+ if err != nil {
70
+ log .Fatal (err )
71
+ }
72
+ resp .Body .Close ()
73
+
74
+ expectedClientID , err := peer .IDFromPrivateKey (clientKey )
75
+ if err != nil {
76
+ log .Fatal (err )
77
+ }
78
+ if observedClientID != expectedClientID .String () {
79
+ log .Fatal ("observedClientID does not match expectedClientID" )
80
+ }
81
+
82
+ observedServerID := libp2phttp .ServerPeerID (resp )
83
+ if observedServerID != expectedServerID {
84
+ log .Fatal ("observedServerID does not match expectedServerID" )
85
+ }
86
+
87
+ fmt .Println ("Successfully authenticated HTTP request" )
88
+ // Output: Successfully authenticated HTTP request
89
+ }
90
+
18
91
func ExampleHost_withAStockGoHTTPClient () {
19
92
server := libp2phttp.Host {
20
93
InsecureAllowHTTP : true , // For our example, we'll allow insecure HTTP
0 commit comments