gorilla / sessions

Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
2.93k stars 371 forks source link

Saving OAuth2 pointer in sessions #257

Closed rhaidiz closed 2 years ago

rhaidiz commented 2 years ago

Describe the problem you're having I'm trying to save a pointer into a session, specifically a OAuth2 configuration, but I'm having some issue.

Versions go version go1.18.1 darwin/amd64

Code! The following piece of code should reproduce the issue. When I go to /puthandler I can see that myConf is stored in the session, but when I go to /gethandler it is nil. I feel like I'm missing something very basic here but for the love of me I cannot figure it out.

package main

import (
    "encoding/gob"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/sessions"
    "golang.org/x/oauth2"
)

var store = sessions.NewCookieStore([]byte("key"))

type Project struct {
    ID   string
    conf *oauth2.Config
}

func PutHandler(w http.ResponseWriter, r *http.Request) {
    sess, err := store.Get(r, "test_sess")
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    myConf := &oauth2.Config{
        ClientID:     "YOUR_CLIENT_ID",
        ClientSecret: "YOUR_CLIENT_SECRET",
        Scopes:       []string{"SCOPE1", "SCOPE2"},
        Endpoint: oauth2.Endpoint{
            AuthURL:  "https://provider.com/o/oauth2/auth",
            TokenURL: "https://provider.com/o/oauth2/token",
        },
    }
    project := Project{ID: "8138ahd913", conf: myConf}
    sess.Values["proj"] = project
    err = sess.Save(r, w)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    fmt.Fprintf(w, "%#v", sess.Values)
}

func GetHandler(w http.ResponseWriter, r *http.Request) {
    sess, err := store.Get(r, "test_sess")
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    fmt.Fprintf(w, "%#v", sess.Values)
}

func main() {
    gob.Register(Project{})

    http.HandleFunc("/puthandler", PutHandler)
    http.HandleFunc("/gethandler", GetHandler)

    log.Fatal(http.ListenAndServe(":8000", nil))
}
rhaidiz commented 2 years ago

I'm an idiot. Variable conf in struct Project is not exported and therefore cannot be serialized. Forget I asked 😄