Skip to content

Instantly share code, notes, and snippets.

@kevinlebrun
Created June 7, 2016 12:32
Show Gist options
  • Save kevinlebrun/928d504ce23cd44b3dd1f1c6ff6bdf41 to your computer and use it in GitHub Desktop.
Save kevinlebrun/928d504ce23cd44b3dd1f1c6ff6bdf41 to your computer and use it in GitHub Desktop.

PoC Keep Session during domain migration

The idea is simple: pass the session cookie from the old domain to the new one.

Usage

$ go run server.go

Go to http://session and http://nosession.

You will need to update your hosts (/etc/hosts):

$ 127.0.0.1 session nosession
<!doctype html>
<html>
<head>
<title>This site has no session</title>
</head>
<body>
<p>Site without session (no cookies on this domain).</p>
<iframe id="session-keeper" src="http://session?query=string" seamless></iframe>
<script>
window.addEventListener('message', function(event) {
if (event.origin === 'http://session') {
console.log('Cookies: ', event.data);
}
});
</script>
</body>
</html>
package main
import (
"fmt"
"io"
"log"
"mime"
"net/http"
"os"
"strings"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":80", mux))
}
func handler(w http.ResponseWriter, r *http.Request) {
host := strings.SplitN(r.Host, ":", 2)[0]
file := host + ".html"
if host == "session" {
cookie := http.Cookie{
Name: "session",
Value: "MySession",
}
http.SetCookie(w, &cookie)
}
f, err := os.Open(file)
if err != nil {
w.WriteHeader(404)
fmt.Fprintf(w, "Not Found: %q", file)
return
}
defer f.Close()
w.Header().Add("Content-Type", mime.TypeByExtension("html"))
io.Copy(w, f)
}
<!doctype html>
<html>
<head>
<title>This site has a session</title>
</head>
<body>
<p>Site with a session.</p>
<script>
function isInIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (isInIframe()) {
window.parent.postMessage(document.cookie, 'http://nosession');
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment