Skip to content

Instantly share code, notes, and snippets.

@olafkotur
Created January 29, 2020 20:35
Show Gist options
  • Save olafkotur/2dacdd601d954ff9ba14fda06ebafcb3 to your computer and use it in GitHub Desktop.
Save olafkotur/2dacdd601d954ff9ba14fda06ebafcb3 to your computer and use it in GitHub Desktop.
JWT Authentication in Golang
// Return JWT header using HS256 algorithm
func generateHeader() (s string) {
header := `{"alg": "HS256", "typ": "JWT"}`
encoded := b64.StdEncoding.EncodeToString([]byte(header))
return strings.TrimRight(encoded, "=")
}
// Return JWT payload with some some example data e.g. expiration and username
func generatePayload(username string) (s string) {
exp := int(time.Now().Add(expThreshold).Unix())
payload := `{"exp": "` + toString(expiration) + `", "username": "` + username + `"}`
encoded := b64.StdEncoding.EncodeToString([]byte(payload))
return strings.TrimRight(encoded, "=")
}
// Return JWT signature using SHA256 including salt
func generateSignature(secret string) (s string) {
hasher := sha256.New()
_, _ = hasher.Write([]byte(secret + salt))
hash := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
return strings.TrimRight(hash, "=")
}
// Return complete JWT token with header, payload and signature
func generateToken(user User) (s string) {
header := generateHeader()
payload := generatePayload(user.Username)
return header + "." + payload + "." + user.Password
}
// Checks whether received token is valid
func authenticateToken(token string) (b bool) {
// Add padding for comparison
components := strings.Split(token, ".")
if i := len(components[1]) % 4; i != 0 {
components[1] += strings.Repeat("=", 4-i)
}
// Decode payload data to get user info
p, _ := b64.StdEncoding.DecodeString(components[1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment