Skip to content

Instantly share code, notes, and snippets.

@chocolatkey
Created December 16, 2020 23:17
Show Gist options
  • Save chocolatkey/3792fee0ac0adecf3aecb76aa9c2ce80 to your computer and use it in GitHub Desktop.
Save chocolatkey/3792fee0ac0adecf3aecb76aa9c2ce80 to your computer and use it in GitHub Desktop.
Express signed cookie parser (for loopback) in go
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"net/http"
"net/url"
"strings"
)
func extractExpressCookie(r *http.Request, secret string) string {
c, err := r.Cookie("access_token")
if err != nil || c == nil {
return ""
}
rawcookie, _ := url.QueryUnescape(c.Value)
if !strings.HasPrefix(rawcookie, "s:") { // Is signed cookie https://github.com/expressjs/cookie-parser/blob/master/index.js#L134
return ""
}
rawcookie = rawcookie[2:]
// Verify cookie signature (https://github.com/tj/node-cookie-signature/blob/master/index.js)
lidx := strings.LastIndex(rawcookie, ".")
if lidx < 1 {
return ""
}
cookieValue := rawcookie[:lidx]
cookieSignature, err := base64.RawStdEncoding.DecodeString(rawcookie[lidx+1:])
if err != nil || len(cookieSignature) == 0 {
return ""
}
macer := hmac.New(sha256.New, secret)
macer.Write([]byte(cookieValue))
sum := macer.Sum(nil)
if subtle.ConstantTimeCompare(cookieSignature, sum) == 0 {
return "" // HMAC does not match cookie signature
}
return cookieValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment