github.com/jcmturner/gokrb5/v8@v8.4.4/examples/example.go (about) 1 // Package examples provides simple examples of gokrb5 use. 2 //go:build examples 3 // +build examples 4 5 package main 6 7 import ( 8 "encoding/hex" 9 "fmt" 10 "io" 11 "log" 12 "net/http" 13 "net/http/httptest" 14 "os" 15 16 "github.com/jcmturner/goidentity/v6" 17 "github.com/jcmturner/gokrb5/v8/client" 18 "github.com/jcmturner/gokrb5/v8/config" 19 "github.com/jcmturner/gokrb5/v8/keytab" 20 "github.com/jcmturner/gokrb5/v8/service" 21 "github.com/jcmturner/gokrb5/v8/spnego" 22 "github.com/jcmturner/gokrb5/v8/test/testdata" 23 ) 24 25 func main() { 26 s := httpServer() 27 defer s.Close() 28 29 b, _ := hex.DecodeString(testdata.KEYTAB_TESTUSER1_TEST_GOKRB5) 30 kt := keytab.New() 31 kt.Unmarshal(b) 32 c, _ := config.NewFromString(testdata.KRB5_CONF) 33 c.LibDefaults.NoAddresses = true 34 cl := client.NewWithKeytab("testuser1", "TEST.GOKRB5", kt, c) 35 httpRequest(s.URL, cl) 36 37 b, _ = hex.DecodeString(testdata.KEYTAB_TESTUSER2_TEST_GOKRB5) 38 kt = keytab.New() 39 kt.Unmarshal(b) 40 c, _ = config.NewFromString(testdata.KRB5_CONF) 41 c.LibDefaults.NoAddresses = true 42 cl = client.NewWithKeytab("testuser2", "TEST.GOKRB5", kt, c) 43 httpRequest(s.URL, cl) 44 } 45 46 func httpRequest(url string, cl *client.Client) { 47 l := log.New(os.Stderr, "GOKRB5 Client: ", log.Ldate|log.Ltime|log.Lshortfile) 48 49 err := cl.Login() 50 if err != nil { 51 l.Printf("Error on AS_REQ: %v\n", err) 52 } 53 r, _ := http.NewRequest("GET", url, nil) 54 err = spnego.SetSPNEGOHeader(cl, r, "HTTP/host.test.gokrb5") 55 if err != nil { 56 l.Printf("Error setting client SPNEGO header: %v", err) 57 } 58 httpResp, err := http.DefaultClient.Do(r) 59 if err != nil { 60 l.Printf("Request error: %v\n", err) 61 } 62 fmt.Fprintf(os.Stdout, "Response Code: %v\n", httpResp.StatusCode) 63 content, _ := io.ReadAll(httpResp.Body) 64 fmt.Fprintf(os.Stdout, "Response Body:\n%s\n", content) 65 } 66 67 func httpServer() *httptest.Server { 68 l := log.New(os.Stderr, "GOKRB5 Service Tests: ", log.Ldate|log.Ltime|log.Lshortfile) 69 b, _ := hex.DecodeString(testdata.HTTP_KEYTAB) 70 kt := keytab.New() 71 kt.Unmarshal(b) 72 th := http.HandlerFunc(testAppHandler) 73 s := httptest.NewServer(spnego.SPNEGOKRB5Authenticate(th, kt, service.Logger(l))) 74 return s 75 } 76 77 func testAppHandler(w http.ResponseWriter, r *http.Request) { 78 creds := goidentity.FromHTTPRequestContext(r) 79 fmt.Fprint(w, "<html>\n<p><h1>TEST.GOKRB5 Handler</h1></p>\n") 80 if creds != nil && creds.Authenticated() { 81 fmt.Fprintf(w, "<ul><li>Authenticed user: %s</li>\n", creds.UserName()) 82 fmt.Fprintf(w, "<li>User's realm: %s</li></ul>\n", creds.Domain()) 83 } else { 84 w.WriteHeader(http.StatusUnauthorized) 85 fmt.Fprint(w, "Authentication failed") 86 } 87 fmt.Fprint(w, "</html>") 88 return 89 }