Authentication and Authorization
What you will learn
By the end of this lesson, you will be able to:
- distinguish authentication from authorization;
- design safe password and session boundaries;
- validate tokens by policy rather than merely decoding them;
- apply authorization to the requested resource;
- recognise the roles of TLS, cookies, CSRF protection, and CORS.
Authentication and authorization are different
Authentication answers: who is making the request?
Authorization answers: may that identity perform this action on this resource?
A valid login does not grant access to every lesson, account, or administrative operation.
Password handling
Never store plaintext passwords or reversible encrypted passwords. Use a maintained password-hashing implementation designed for passwords, with parameters selected from current security guidance.
Keep hashing behind a narrow interface:
type PasswordHasher interface {
Hash(password string) (string, error)
Compare(encodedHash, password string) error
}
This keeps business logic independent of one implementation and permits parameter upgrades. Do not invent a hashing algorithm or use a fast general-purpose hash such as plain SHA-256 for password storage.
Login errors should not reveal whether an email exists. Apply rate limiting and monitoring at an appropriate boundary, and consider multi-factor authentication for sensitive systems.
Server-side sessions
A common browser design stores an opaque random session ID in a cookie and keeps session state on the server.
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: opaqueSessionID,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
MaxAge: 3600,
})
HttpOnlyprevents normal JavaScript access but does not remove all cross-site scripting risk.Securesends the cookie only over HTTPS.SameSitereduces some cross-site request scenarios; choose the mode from the application's actual flows.- Rotate the session ID after login or privilege changes.
- Expire and revoke sessions server-side when required.
Session identifiers require enough cryptographic randomness. Generate them with crypto/rand, encode them safely, and never include user information or secrets directly in the token.
Token authentication
A signed token is not automatically trustworthy because it can be parsed. Validation must enforce the expected:
- signature algorithm and trusted key;
- issuer;
- audience;
- expiration and not-before rules;
- token purpose and required claims.
Use a maintained library, lock the algorithm and policy in configuration, and test rejection cases. Do not accept an algorithm merely because the token header requests it.
Short token lifetimes reduce exposure but do not provide instant revocation by themselves. Design rotation and revocation according to the threat model.
Authentication middleware
Middleware can verify credentials and put a small identity value into request context:
type Identity struct {
UserID string
Roles []string
}
func IdentityFromContext(ctx context.Context) (Identity, bool) {
identity, ok := ctx.Value(identityKey).(Identity)
return identity, ok
}
Do not store passwords, raw tokens, or database connections in context.
Authorize the resource
func (s *Service) UpdateLesson(ctx context.Context, actor UserID, lessonID LessonID, input Update) error {
lesson, err := s.repository.Find(ctx, lessonID)
if err != nil {
return err
}
if lesson.OwnerID != actor && !s.permissions.IsAdmin(actor) {
return ErrForbidden
}
return s.repository.Update(ctx, lessonID, input)
}
Checking only “has role editor” may be insufficient when access depends on tenancy, ownership, state, or field. Enforce permissions at the application boundary even if the UI hides unavailable controls.
CSRF, CORS, and TLS
- TLS protects credentials and traffic in transit. Production authentication must use HTTPS end to end across untrusted networks.
- CSRF matters when browsers automatically attach credentials such as cookies. Use an appropriate CSRF defence in addition to deliberate SameSite settings.
- CORS controls which browser origins may read responses. It is not authentication and does not stop non-browser clients.
Security headers and proxy configuration must match the deployment. Only trust forwarded headers from known proxies.
Secrets
Load signing keys, database credentials, and client secrets from an approved secret-management mechanism. Do not commit them, expose them through diagnostics, include them in URLs, or log them.
Plan rotation before an incident requires it.
Common mistakes
- Decoding a token without validating its policy: attacker-controlled claims become trusted identity.
- Authorizing only by route: resource ownership and tenant boundaries are missed.
- Returning “email not found” during login: account enumeration becomes easier.
- Putting bearer tokens in URLs: logs, history, and referrers can retain them.
- Treating CORS as an access-control system: non-browser requests ignore it.
- Writing custom cryptography: subtle design and implementation errors become security vulnerabilities.
Practice
Design authentication for a browser-based lesson application. Include login, session creation, authenticated context, owner/admin authorization, logout, session expiry, CSRF protection, and safe error responses.
POST /sessions
validate bounded input
load account by canonical login identifier
compare password hash with constant policy
return the same public failure for unknown account or wrong password
generate opaque random session ID
store only a hash of the session ID when threat model requires it
set Secure + HttpOnly + deliberate SameSite cookie
Authenticated middleware
read cookie
hash/lookup active session
check expiry and account state
place minimal Identity in request context
Application service
load requested lesson
check owner, tenant, and admin rules
reject with a stable domain error
POST /logout
require CSRF protection for cookie-authenticated request
revoke server-side session
expire cookie
Use generic public authentication failures while logging a safe internal classification. Rate limiting should consider account, network, and distributed deployment realities without permanently blocking legitimate shared networks.
Summary
- Authentication proves identity; authorization decides access to a concrete action and resource.
- Use maintained password-hashing and token libraries with explicit policies.
- Protect browser sessions with opaque identifiers and deliberate cookie settings.
- Enforce authorization in application logic, not only in the interface or router.
- Treat TLS, CSRF, CORS, secret storage, and rotation as separate security concerns.
Official reference: Security best practices for Go developers.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.