MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / TestCookieAuth

Function TestCookieAuth

pkg/webmiddleware/cookie_auth_test.go:29–89  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

27)
28
29func TestCookieAuth(t *testing.T) {
30 a := assertions.New(t)
31 sc := securecookie.New(
32 []byte("1234123412341234123412341234123412341234123412341234123412341234"),
33 []byte("12341234123412341234123412341234"),
34 )
35 m := CookieAuth("_session")
36 cookieMiddleware := Cookies(
37 []byte("1234123412341234123412341234123412341234123412341234123412341234"),
38 []byte("12341234123412341234123412341234"),
39 )
40 authCookie := &auth.CookieShape{
41 UserID: "test-user",
42 SessionID: "id-1234",
43 SessionSecret: "secret-1234",
44 }
45 encoded, _ := sc.Encode("_session", authCookie)
46 cookie := &http.Cookie{
47 Name: "_session",
48 Value: encoded,
49 Path: "/",
50 Secure: true,
51 HttpOnly: true,
52 }
53
54 t.Run("Forwards cookie value to auth header", func(t *testing.T) {
55 r := httptest.NewRequest(http.MethodPut, "/", nil)
56 rec := httptest.NewRecorder()
57 r.AddCookie(cookie)
58
59 cookieMiddleware(
60 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
61 a.So(r.Header.Get("Authorization"), should.Equal, "Bearer "+auth.JoinToken(auth.SessionToken, "id-1234", "secret-1234"))
62 })),
63 ).ServeHTTP(rec, r)
64 res := rec.Result()
65
66 a.So(res.StatusCode, should.Equal, http.StatusOK)
67 })
68
69 t.Run("Does not overwrite existing auth header", func(t *testing.T) {
70 r := httptest.NewRequest(http.MethodPut, "/", nil)
71 rec := httptest.NewRecorder()
72 r.AddCookie(cookie)
73 r.Header.Set("Authorization", "Bearer 1234")
74
75 cookieMiddleware(
76 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
77 a.So(r.Header.Get("Authorization"), should.Equal, "Bearer 1234")
78 })),
79 ).ServeHTTP(rec, r)
80
81 res := rec.Result()
82 cookies := r.Cookies()
83
84 a.So(cookies, should.HaveLength, 1)
85 a.So(cookies[0].Name, should.Equal, "_session")
86 a.So(cookies[0].Value, should.NotBeEmpty)

Callers

nothing calls this directly

Calls 10

JoinTokenFunction · 0.92
CookieAuthFunction · 0.85
CookiesFunction · 0.85
NewMethod · 0.65
EncodeMethod · 0.65
RunMethod · 0.65
GetMethod · 0.65
ResultMethod · 0.65
SetMethod · 0.65
ServeHTTPMethod · 0.45

Tested by

no test coverage detected