Debian Codegraph @

examples/example.go

raw symbols SCIP
1 // +build examples
2
3 package main
4
5 import (
6 "encoding/hex"
7 "fmt"
8 "gopkg.in/jcmturner/gokrb5.v5/client"
9 "gopkg.in/jcmturner/gokrb5.v5/config"
10 "gopkg.in/jcmturner/gokrb5.v5/credentials"
11 "gopkg.in/jcmturner/gokrb5.v5/keytab"
12 "gopkg.in/jcmturner/gokrb5.v5/service"
13 "gopkg.in/jcmturner/gokrb5.v5/testdata"
14 "io/ioutil"
15 "log"
16 "net/http"
17 "net/http/httptest"
18 "os"
19 )
20
21 func main() {
22 s := httpServer()
23 defer s.Close()
24
25 b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
26 kt, _ := keytab.Parse(b)
27 c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
28 c.LibDefaults.NoAddresses = true
29 cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt)
30 cl.WithConfig(c)
31 httpRequest(s.URL, cl)
32
33 b, _ = hex.DecodeString(testdata.TESTUSER2_KEYTAB)
34 kt, _ = keytab.Parse(b)
35 c, _ = config.NewConfigFromString(testdata.TEST_KRB5CONF)
36 c.LibDefaults.NoAddresses = true
37 cl = client.NewClientWithKeytab("testuser2", "TEST.GOKRB5", kt)
38 cl.WithConfig(c)
39 httpRequest(s.URL, cl)
40 }
41
42 func httpRequest(url string, cl client.Client) {
43 l := log.New(os.Stderr, "GOKRB5 Client: ", log.Ldate|log.Ltime|log.Lshortfile)
44
45 err := cl.Login()
46 if err != nil {
47 l.Printf("Error on AS_REQ: %v\n", err)
48 }
49 r, _ := http.NewRequest("GET", url, nil)
50 err = cl.SetSPNEGOHeader(r, "HTTP/host.test.gokrb5")
51 if err != nil {
52 l.Printf("Error setting client SPNEGO header: %v", err)
53 }
54 httpResp, err := http.DefaultClient.Do(r)
55 if err != nil {
56 l.Printf("Request error: %v\n", err)
57 }
58 fmt.Fprintf(os.Stdout, "Response Code: %v\n", httpResp.StatusCode)
59 content, _ := ioutil.ReadAll(httpResp.Body)
60 fmt.Fprintf(os.Stdout, "Response Body:\n%s\n", content)
61 }
62
63 func httpServer() *httptest.Server {
64 l := log.New(os.Stderr, "GOKRB5 Service: ", log.Ldate|log.Ltime|log.Lshortfile)
65 b, _ := hex.DecodeString(testdata.HTTP_KEYTAB)
66 kt, _ := keytab.Parse(b)
67 th := http.HandlerFunc(testAppHandler)
68 s := httptest.NewServer(service.SPNEGOKRB5Authenticate(th, kt, "", false, l))
69 return s
70 }
71
72 func testAppHandler(w http.ResponseWriter, r *http.Request) {
73 ctx := r.Context()
74 fmt.Fprint(w, "<html>\n<p><h1>TEST.GOKRB5 Handler</h1></p>\n")
75 if validuser, ok := ctx.Value(service.CTXKeyAuthenticated).(bool); ok && validuser {
76 if creds, ok := ctx.Value(service.CTXKeyCredentials).(credentials.Credentials); ok {
77 fmt.Fprintf(w, "<ul><li>Authenticed user: %s</li>\n", creds.Username)
78 fmt.Fprintf(w, "<li>User's realm: %s</li></ul>\n", creds.Realm)
79 }
80
81 } else {
82 w.WriteHeader(http.StatusUnauthorized)
83 fmt.Fprint(w, "Authentication failed")
84 }
85 fmt.Fprint(w, "</html>")
86 return
87 }