github.com/jcmturner/gokrb5/v8@v8.4.4/examples/httpClient.go (about)

     1  //go:build examples
     2  // +build examples
     3  
     4  package main
     5  
     6  import (
     7  	"encoding/hex"
     8  	"fmt"
     9  	"io"
    10  	"log"
    11  	"net/http"
    12  	"os"
    13  
    14  	"github.com/jcmturner/gokrb5/v8/client"
    15  	"github.com/jcmturner/gokrb5/v8/config"
    16  	"github.com/jcmturner/gokrb5/v8/keytab"
    17  	"github.com/jcmturner/gokrb5/v8/spnego"
    18  	"github.com/jcmturner/gokrb5/v8/test/testdata"
    19  )
    20  
    21  const (
    22  	port     = ":9080"
    23  	kRB5CONF = `[libdefaults]
    24    default_realm = TEST.GOKRB5
    25    dns_lookup_realm = false
    26    dns_lookup_kdc = false
    27    ticket_lifetime = 24h
    28    forwardable = yes
    29    default_tkt_enctypes = aes256-cts-hmac-sha1-96
    30    default_tgs_enctypes = aes256-cts-hmac-sha1-96
    31  
    32  [realms]
    33   TEST.GOKRB5 = {
    34    kdc = 127.0.0.1:88
    35    admin_server = 127.0.0.1:749
    36    default_domain = test.gokrb5
    37   }
    38  
    39  [domain_realm]
    40   .test.gokrb5 = TEST.GOKRB5
    41   test.gokrb5 = TEST.GOKRB5
    42   `
    43  )
    44  
    45  func main() {
    46  	l := log.New(os.Stderr, "GOKRB5 Client: ", log.LstdFlags)
    47  
    48  	//defer profile.Start(profile.TraceProfile).Stop()
    49  	// Load the keytab
    50  	kb, _ := hex.DecodeString(testdata.KEYTAB_TESTUSER2_TEST_GOKRB5)
    51  	kt := keytab.New()
    52  	err := kt.Unmarshal(kb)
    53  	if err != nil {
    54  		l.Fatalf("could not load client keytab: %v", err)
    55  	}
    56  
    57  	// Load the client krb5 config
    58  	conf, err := config.NewFromString(kRB5CONF)
    59  	if err != nil {
    60  		l.Fatalf("could not load krb5.conf: %v", err)
    61  	}
    62  	addr := os.Getenv("TEST_KDC_ADDR")
    63  	if addr != "" {
    64  		conf.Realms[0].KDC = []string{addr + ":88"}
    65  	}
    66  
    67  	// Create the client with the keytab
    68  	cl := client.NewWithKeytab("testuser2", "TEST.GOKRB5", kt, conf, client.Logger(l), client.DisablePAFXFAST(true))
    69  
    70  	// Log in the client
    71  	err = cl.Login()
    72  	if err != nil {
    73  		l.Fatalf("could not login client: %v", err)
    74  	}
    75  
    76  	// Form the request
    77  	url := "http://localhost" + port
    78  	r, err := http.NewRequest("GET", url, nil)
    79  	if err != nil {
    80  		l.Fatalf("could create request: %v", err)
    81  	}
    82  
    83  	spnegoCl := spnego.NewClient(cl, nil, "HTTP/host.test.gokrb5")
    84  
    85  	// Make the request
    86  	resp, err := spnegoCl.Do(r)
    87  	if err != nil {
    88  		l.Fatalf("error making request: %v", err)
    89  	}
    90  	b, err := io.ReadAll(resp.Body)
    91  	if err != nil {
    92  		l.Fatalf("error reading response body: %v", err)
    93  	}
    94  	fmt.Println(string(b))
    95  }