Prompt
How do I protect API endpoints with user authentication?
Latest observation
Oct 14, 2026
OpenAI APIWeb search: off
To protect API endpoints with user authentication, the core idea is:
- Verify who the user is
- Check that they’re allowed to access the endpoint
- Deny requests that don’t pass
Common approaches
1) Session-based authentication
- User logs in with username/password.
- Server creates a session.
- Client sends a session cookie on future requests.
- Server looks up the session and identifies the user.
Good for: traditional web apps, same-site browser clients
Protect with: HttpOnly, Secure, SameSite cookies
2) Token-based authentication
- User logs in and receives a token, often a JWT or opaque access token.
- Client sends it in the
Authorizationheader:
Authorization: Bearer <token>
- API verifies the token on each request.
Good for: mobile apps, SPAs, third-party APIs, microservices
Basic flow for protecting an endpoint
Step 1: Require authentication middleware
Add middleware that:
- Reads the credential (cookie or bearer token)
- Validates it
- Loads the user identity
- Rejects unauthenticated requests with
401 Unauthorized
Step 2: Add authorization checks
After authentication, check whether the user can do the action:
- Is the user an admin?
- Do they own this resource?
- Do they have the required scope/role?
If not, return 403 Forbidden.
Example: Bearer token protected endpoint
Request
GET /api/profile
Authorization: Bearer eyJhbGciOi...
Server logic
- Extract token from
Authorizationheader - Validate signature / expiration
- Identify user from token claims
- If valid, continue to handler
- If invalid/missing, return
401
Example pseudocode
def auth_middleware(request):
auth = request.headers.get("Authorization")
if not auth or not auth.startswith("Bearer "):
return 401
token = auth.removeprefix("Bearer ").strip()
user = validate_token(token) # check signature, expiry, issuer, etc.
if not user:
return 401
request.user = user
return next_handler(request)
Then in the endpoint:
def get_profile(request):
if not request.user:
return 401
return {"id": request.user.id, "email": request.user.email}
Security best practices
- Always use HTTPS
- Use short-lived access tokens
- Rotate refresh tokens carefully if you use them
- Validate token expiration, issuer, audience
- Don’t put secrets in client-side code
- Return 401 for unauthenticated, 403 for unauthorized
- Log auth failures, but don’t leak sensitive details
- Protect against CSRF if you use cookies for auth
Which should you choose?
- Browser app with same domain: session cookies are often simplest
- SPA/mobile/API: bearer tokens or JWTs
- Internal service-to-service: OAuth2 client credentials, mTLS, or signed tokens
If you want, I can show you how to implement this in a specific framework like Express, FastAPI, Django, Spring Boot, or Flask.