DartAdvanced 2 min read

Dart backend authentication and authorization: verify identity and ownership

Verify a trusted identity and enforce resource ownership instead of trusting client-supplied user IDs.

On this page

Authentication establishes identity; authorization decides what that identity may do. A valid token is not sufficient evidence that a caller owns a particular task. Keep both checks on the server for every protected operation.

Choose a trusted identity system

For a production application, use a supported identity provider or a reviewed authentication system. Verify token signature, issuer, audience, expiry and other provider-specific requirements using the provider’s supported verification flow. Base64-decoding a JWT payload is not verification.

Keep privileged signing keys and service-account credentials in server configuration. Do not embed them in Flutter binaries, browser source, tutorial snippets or a shared DTO package. Plan refresh, expiry and revocation behavior according to the selected provider.

Attach only verified identity to request context

An authentication middleware can put a verified user identifier in a trusted request context. Application handlers then use that value. Never accept an owner ID from a normal request body or an arbitrary X-User header as proof of identity.

Bearer token -> supported verifier -> trusted principal
trusted principal + task ID -> ownership policy -> repository operation

This is an architecture flow, not a complete authentication implementation. The teaching API intentionally has no identity provider and must stay local until those responsibilities are implemented.

Enforce ownership in the data operation

A read or update should constrain both resource ID and authorized owner in storage. Avoid loading an arbitrary user’s record and only hiding its content later in a widget. Choose deliberately whether a non-owned resource returns 403 or a non-disclosing 404, then test that contract consistently.

For cookie-based browser sessions, include secure cookie attributes and a CSRF strategy. For bearer tokens, control storage and transmission and use TLS. Add rate limiting and audit behavior at the service boundary; CORS alone does not provide any of these controls.

Test the adversarial path

Test missing credentials, expired/invalid credentials, a valid user accessing their resource and another valid user attempting the same ID. Confirm no private fields or internal exception details appear in rejected responses.

Exercise

Design an injected verifier interface and a fake for handler tests. Describe the production provider adapter separately. Add an ownership column to your database schema and verify that every read/update/delete path constrains it.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.