Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 43

    Security Best Practices

    Go backend security spans input validation, SQL injection prevention, authentication (JWT, OAuth2), HTTPS/TLS, secrets management, and dependency scanning.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Go backend security spans input validation, SQL injection prevention, authentication (JWT, OAuth2), HTTPS/TLS, secrets management, and dependency scanning. Go's memory safety prevents buffer overflows, but application-level vulnerabilities remain your responsibility.

    OWASP Top 10 applies: broken access control, injection, insecure design. Use golang.org/x/crypto/bcrypt for passwords, crypto/rand for tokens, and run govulncheck in CI. Interviewers ask JWT validation, CORS, rate limiting, and secret storage.

    This lesson covers JWT middleware, parameterized queries, security headers, and dependency vulnerability scanning — production security checklist for Go APIs.

    The story

    A fintech API gateway validates JWT signatures with pinned public keys, enforces TLS 1.3 for all outbound calls to payment processors, and sanitizes SQL parameters through prepared statements — never string concatenation. When Cloudflare mitigates a DDoS, the origin Go service must still reject forged internal headers and rate-limit authenticated abuse.

    Security in Go layers defense: crypto/rand for tokens, bcrypt for passwords, middleware for auth, and regular govulncheck scans in CI for known CVEs in dependencies.

    Understanding the topic

    Key concepts

    • Parameterized SQL — never string concat user input.
    • bcrypt.HashPassword for storage; constant-time compare.
    • JWT: validate signature, exp, iss; don't trust claims without verify.
    • crypto/rand for tokens — never math/rand for secrets.
    • HTTPS only in production; HSTS header.
    • govulncheck scans module vulnerabilities.

    Step-by-step explanation

    1. Middleware validates JWT on protected routes.
    2. RBAC checks role claim against required permission.
    3. Rate limiter per IP prevents brute force.
    4. Input validation on all external data.
    5. Secrets from env/vault — rotated regularly.
    6. CI runs govulncheck and docker scan on every build.

    Practical code example

    Security middleware with headers, body limit, and JWT auth stub:

    go
    package main
    import (
    "context"
    "net/http"
    "strings"
    )
    type ctxKey string
    const userIDKey ctxKey = "userID"
    func securityHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.Header().Set("X-Frame-Options", "DENY")
    w.Header().Set("Strict-Transport-Security", "max-age=31536000")
    next.ServeHTTP(w, r)
    })
    }
    func maxBody(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1MB
    next.ServeHTTP(w, r)
    })
    }
    func jwtAuth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    auth := r.Header.Get("Authorization")
    if !strings.HasPrefix(auth, "Bearer ") {
    http.Error(w, "unauthorized", http.StatusUnauthorized)
    return
    }
    token := strings.TrimPrefix(auth, "Bearer ")
    // validateJWT(token) — verify signature, exp, issuer
    if token == "" {
    http.Error(w, "invalid token", http.StatusUnauthorized)
    return
    }
    ctx := context.WithValue(r.Context(), userIDKey, "user-123")
    next.ServeHTTP(w, r.WithContext(ctx))
    })
    }
    func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /api/profile", func(w http.ResponseWriter, r *http.Request) {
    uid := r.Context().Value(userIDKey)
    w.Write([]byte("profile:" + uid.(string)))
    })
    handler := securityHeaders(maxBody(jwtAuth(mux)))
    http.ListenAndServe(":8080", handler)
    }

    Line-by-line code explanation

    • type ctxKey string defines a private type for context keys. A key of this type cannot clash with keys that other packages put in the same context, even if they use the same string.
    • w.Header().Set("X-Content-Type-Options", "nosniff") is one of three headers set by securityHeaders. It tells browsers not to guess a content type. The other two are X-Frame-Options DENY, which blocks framing, and Strict-Transport-Security.
    • w.Header().Set("Strict-Transport-Security", "max-age=31536000") tells browsers to use HTTPS for this site for the next 31,536,000 seconds, which is one year. Browsers only honor it when it arrives over HTTPS.
    • r.Body = http.MaxBytesReader(w, r.Body, 1<<20) replaces the request body with one that allows at most 1<<20 bytes, which is 1 MB. Reading past that fails with an error, so the limit takes effect when a handler reads the body.
    • if !strings.HasPrefix(auth, "Bearer ") { checks that the Authorization header starts with Bearer and a space. If not, the middleware sends 401 unauthorized and returns without calling the next handler.
    • if token == "" { rejects a header that was just Bearer with nothing after it. The comment above it marks where real JWT validation belongs, but the code itself only checks that the token is not empty.
    • ctx := context.WithValue(r.Context(), userIDKey, "user-123") makes a new context that carries a user id. The id is hard-coded here, and next.ServeHTTP(w, r.WithContext(ctx)) passes the request on with that context attached.
    • uid := r.Context().Value(userIDKey) reads the user id back inside the /api/profile handler. Value returns an any, so uid.(string) is a type assertion that would panic if the value were missing.
    • handler := securityHeaders(maxBody(jwtAuth(mux))) stacks the middleware. A request passes through securityHeaders first, then maxBody, then jwtAuth, and only then reaches the router.

    Key takeaway: This code only checks that a bearer token is present and not empty. It does not verify a signature, expiry or issuer, so it is not real authentication until proper JWT validation is added. The security headers and the body size limit wrap the whole router, so they apply to every route.

    Real-world use

    Where you'll use this in production

    • OAuth2 login flows with Google/GitHub providers.
    • API key authentication for developer portals.
    • PCI-compliant payment APIs with audit logging.
    • Zero-trust internal service mTLS on service mesh.

    Best practices

    • Validate all input; whitelist acceptable values.
    • Use bcrypt/scrypt for passwords; never store plaintext.
    • Short-lived JWT with refresh token rotation.
    • Run govulncheck and dependabot in CI.
    • Principle of least privilege for DB and cloud IAM.
    • Security headers on all HTTP responses.

    Common mistakes

    • SQL string concatenation with user input.
    • JWT alg:none attack — whitelist allowed algorithms.
    • Secrets in git history or Docker layers.
    • CORS * with credentials enabled.
    • Logging Authorization headers.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionPrevent SQL injection in Go?+

    Answer

    Parameterized queries with $1/? placeholders — never fmt.Sprintf SQL.
    2BeginnerQuestionSecure random tokens?+

    Answer

    crypto/rand.Read — not math/rand.
    3IntermediateQuestionJWT validation checklist?+

    Answer

    Verify signature, exp not passed, iss/aud match, use HTTPS transmission.
    4IntermediateQuestiongovulncheck purpose?+

    Answer

    Scans dependencies against Go vulnerability database.
    5AdvancedQuestionSecure public REST API design.+

    Answer

    HTTPS, JWT/OAuth, rate limit, input validation, WAF, audit log, no verbose errors, dependency scanning.

    Summary

    Parameterized SQL, bcrypt passwords, crypto/rand tokens. Validate JWT properly; security headers on all responses. Secrets in vault/env — never in source or images. govulncheck in CI for dependency vulnerabilities. Next lesson: deployment basics.

    Ready to mark this lesson complete?Track your journey across the entire course.