CodeBlanks Logo Icon CodeBlanks

Headers

Learn headers and authorization.

Headers

HTTP headers add metadata to requests and responses. Common headers: content-type (body type), authorization (token), accept (expected response type).

In Dart headers are a Map<String, String>: {'content-type': 'application/json', 'authorization': 'Bearer xyz'}.

Header keys are case-insensitive. Multiple values can be joined with commas.

The Bearer token pattern

In OAuth/JWT-based authentication, the authorization header takes the form Bearer <token>. Example: {'authorization': 'Bearer eyJhb...'}.

The token is usually obtained from a login endpoint and sent in this header on subsequent requests. The server validates the token and identifies the request.

Never put the token in the URL; it leaks in logs. Always use a header and store the token securely.

Practice Build a headers Map

Inside main add var headers = {'content-type': 'application/json', 'authorization': 'Bearer xyz123'};. Add print(headers.length);.

Starter code

main.dart
void main() {
  // build a Map with two headers; print its length
}

Sample solution

main.dart
void main() {
  var headers = {
    'content-type': 'application/json',
    'authorization': 'Bearer xyz123',
  };
  print(headers.length);
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the Authorization header carry?

  • Body
  • Token/identity Correct answer
  • URL
  • Method

Explanation: the authorization header carries token/identity.

2 Match the headers

Term Meaning
content-type Body type
authorization Token
accept Expected type
cache-control Cache

3 Bearer token header

Question
var headers = {'authorization': '____ $token'};
Answer
var headers = {'authorization': 'Bearer $token'};

Explanation: 'Bearer $token' is the JWT/OAuth token pattern.

All lessons in Advanced