Authentication

suggest change

Authentication answers "who is making this request?". Authorization answers "is this user allowed to do it?". A server usually authenticates a user once, with a password or some other proof, and then gives the client a credential to send with every later request:

Credential Sent as Typical use
Username and password on every request Authorization: Basic ... internal tools, scripts, admin pages
Session ID a cookie browser apps. See Sessions and Cookies
Opaque bearer token Authorization: Bearer ... mobile and single-page apps calling an API
Signed token (JWT) Authorization: Bearer ... stateless APIs, tokens shared between services. See JWT
API key a header such as Authorization or X-Api-Key programs calling an API on behalf of an account
Login through Google, GitHub etc. an access token from the provider "Sign in with ...". See OAuth

This article covers the parts you write yourself in a Dart server and client:

Packages used:

dart pub add shelf shelf_router http crypto cryptography

The examples were run with Dart 3.13, shelf 1.4.3, shelf_router 1.1.5, http 1.6.0, crypto 3.0.7 and cryptography 2.9.0. The servers listen on port 0, which makes the OS pick a free port, and the same program then acts as the client, so each example runs with a single dart run.

Storing passwords

Never store passwords, encrypted passwords, or plain SHA-256 hashes of them. Store the output of a slow, salted password hashing function such as Argon2id. The Cryptography article explains Argon2id and the PHC string format in detail. Here is a compact version with two additions a login system needs: hashing runs in a separate isolate so a busy server isn't blocked for hundreds of milliseconds, and needsRehash() tells you when a stored hash uses outdated parameters.

Save it as bin/passwords.dart. Later examples import it.

import 'dart:convert';
import 'dart:isolate';
import 'dart:math';

import 'package:cryptography/cryptography.dart';

// OWASP minimum for Argon2id: 19 MiB memory, 2 iterations, parallelism 1.
const memoryKiB = 19456;
const iterations = 2;

String _b64(List<int> b) => base64.encode(b).replaceAll('=', '');
List<int> _unb64(String s) => base64.decode(base64.normalize(s));

Future<List<int>> _argon2(String password, List<int> salt, int m, int t) =>
    Isolate.run(() async {
      final algo =
          Argon2id(memory: m, iterations: t, parallelism: 1, hashLength: 32);
      final key =
          await algo.deriveKeyFromPassword(password: password, nonce: salt);
      return key.extractBytes();
    });

Future<String> hashPassword(String password) async {
  final rng = Random.secure();
  final salt = List<int>.generate(16, (_) => rng.nextInt(256));
  final hash = await _argon2(password, salt, memoryKiB, iterations);
  return '\$argon2id\$v=19\$m=$memoryKiB,t=$iterations,p=1'
      '\$${_b64(salt)}\$${_b64(hash)}';
}

Future<bool> verifyPassword(String password, String stored) async {
  final parts = stored.split('\$');
  if (parts.length != 6 || parts[1] != 'argon2id') return false;
  final params = Uri.splitQueryString(parts[3].replaceAll(',', '&'));
  final actual = await _argon2(password, _unb64(parts[4]),
      int.parse(params['m']!), int.parse(params['t']!));
  return Mac(actual) == Mac(_unb64(parts[5])); // constant-time ==
}

/// True if [stored] was made with weaker parameters than the current ones.
bool needsRehash(String stored) =>
    !stored.startsWith('\$argon2id\$v=19\$m=$memoryKiB,t=$iterations,p=1\$');

Future<void> main() async {
  final sw = Stopwatch()..start();
  final stored = await hashPassword('correct horse battery staple');
  print('hash:   $stored');
  print('took:   ${sw.elapsedMilliseconds} ms');

  print('right:  ${await verifyPassword('correct horse battery staple', stored)}');
  print('wrong:  ${await verifyPassword('Tr0ub4dor&3', stored)}');

  const old = r'$argon2id$v=19$m=4096,t=1,p=1$c2FsdHNhbHQ$aGFzaA';
  print('rehash new: ${needsRehash(stored)}, old: ${needsRehash(old)}');
}

Output (the salt and hash differ on every run):

hash:   $argon2id$v=19$m=19456,t=2,p=1$zYdLNDcm7WfI3lI/o7WPsQ$n5FQekX7u5hN9QO5f0HPzSzdh6qHNlZrRjce77mwKLw
took:   216 ms
right:  true
wrong:  false
rehash new: false, old: true

Isolate.run() copies the arguments to a new isolate, runs the closure there and sends the result back. See Isolates. One hash takes about a third of a second of CPU time, and that's the point: an attacker who steals the database can test only a few guesses per second per core. It also means a login endpoint is easy to overload, which is one more reason to rate-limit it (see below).

When a user logs in successfully and needsRehash() returns true, hash the password they just typed with the current parameters and save it. That's the only moment you have the plain password.

Rules for the passwords themselves, following NIST SP 800-63B:

HTTP Basic authentication

With Basic authentication the client sends username:password, Base64-encoded, in the Authorization header of every request. Base64 is not encryption, so use it only over HTTPS (see TLS and HTTPS). It needs no login page and no session storage, which makes it a good fit for internal tools and scripts.

A Shelf middleware wraps a handler: it can reject the request or pass it on, optionally adding values to request.context:

import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;

import 'passwords.dart';

/// Returns (username, password) from an `Authorization: Basic ...` header.
(String, String)? parseBasicAuth(String? header) {
  if (header == null) return null;
  final space = header.indexOf(' ');
  if (space < 0 || header.substring(0, space).toLowerCase() != 'basic') {
    return null;
  }
  try {
    final decoded = utf8.decode(base64.decode(header.substring(space + 1)));
    final colon = decoded.indexOf(':'); // the password may contain ':'
    if (colon < 0) return null;
    return (decoded.substring(0, colon), decoded.substring(colon + 1));
  } on FormatException {
    return null;
  }
}

Middleware basicAuth(Map<String, String> users, {String realm = 'admin'}) {
  // A Response can be sent only once, so build a new one every time.
  Response challenge() => Response.unauthorized('Authentication required\n',
      headers: {'WWW-Authenticate': 'Basic realm="$realm", charset="UTF-8"'});

  return (Handler inner) => (Request request) async {
        final creds = parseBasicAuth(request.headers['authorization']);
        if (creds == null) return challenge();
        final (name, password) = creds;
        final stored = users[name];
        if (stored == null || !await verifyPassword(password, stored)) {
          return challenge();
        }
        return inner(request.change(context: {'user': name}));
      };
}

Future<void> main() async {
  final users = {'admin': await hashPassword('s3cret:with:colons')};

  final handler = const Pipeline()
      .addMiddleware(basicAuth(users))
      .addHandler((req) => Response.ok('Hello, ${req.context['user']}!\n'));
  // Port 0: the OS picks a free port.
  final server = await io.serve(handler, InternetAddress.loopbackIPv4, 0);
  final url = Uri.parse('http://localhost:${server.port}/');

  String basic(String user, String pass) =>
      'Basic ${base64.encode(utf8.encode('$user:$pass'))}';

  for (final (label, headers) in [
    ('no credentials', <String, String>{}),
    ('wrong password', {'authorization': basic('admin', 'guess')}),
    ('right password', {'authorization': basic('admin', 's3cret:with:colons')}),
  ]) {
    final r = await http.get(url, headers: headers);
    print('$label: ${r.statusCode} ${r.body.trim()}');
    if (r.statusCode == 401) {
      print('  WWW-Authenticate: ${r.headers['www-authenticate']}');
    }
  }

  await server.close();
}

Output:

no credentials: 401 Authentication required
  WWW-Authenticate: Basic realm="admin", charset="UTF-8"
wrong password: 401 Authentication required
  WWW-Authenticate: Basic realm="admin", charset="UTF-8"
right password: 200 Hello, admin!

Notes:

On the client side package:http has no special support: build the header yourself as basic() does above. dart:io's HttpClient also accepts credentials through addCredentials() or in the URL's user info (http://user:pass@host/).

Login with bearer tokens

The most common setup for an API used by a mobile or single-page app:

  1. The client sends the username and password to POST /login.
  2. The server checks them and returns a long random token.
  3. The client sends Authorization: Bearer <token> with every request.
  4. POST /logout deletes the token on the server.

The token is opaque: it means nothing by itself, the server looks it up. Compared to a JWT this costs one lookup per request (in a map, Redis or a database table), but logout and revocation take effect instantly, and the token carries no data a client could read. See JWT for the stateless alternative.

The server stores only the SHA-256 hash of each token. If the session table leaks, the hashes can't be used to make requests. A fast hash is fine here, unlike for passwords, because the token is 256 random bits and can't be guessed.

import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

import 'passwords.dart';

class User {
  User(this.name, this.passwordHash, {this.roles = const {}});
  final String name;
  String passwordHash;
  final Set<String> roles;
}

class Session {
  Session(this.userName, this.expiresAt);
  final String userName;
  final DateTime expiresAt;
}

const tokenLifetime = Duration(hours: 1);

final users = <String, User>{};
// Keyed by SHA-256 of the token, so a leaked table can't be used to log in.
final sessions = <String, Session>{};
late final String dummyHash;

String newToken() {
  final rng = Random.secure();
  return base64Url
      .encode(List<int>.generate(32, (_) => rng.nextInt(256)))
      .replaceAll('=', '');
}

String tokenKey(String token) => sha256.convert(utf8.encode(token)).toString();

Response jsonResponse(int status, Object body, {Map<String, String>? headers}) =>
    Response(status,
        body: jsonEncode(body),
        headers: {'content-type': 'application/json', ...?headers});

/// Allows [maxFailures] failed logins per username within [window].
class LoginThrottle {
  LoginThrottle({this.maxFailures = 5, this.window = const Duration(minutes: 15)});
  final int maxFailures;
  final Duration window;
  final _failures = <String, List<DateTime>>{};

  /// How long the caller must wait, or null if it may try now.
  Duration? retryAfter(String key) {
    final now = DateTime.now();
    final list = _failures[key]?..removeWhere((t) => now.difference(t) > window);
    if (list == null || list.length < maxFailures) return null;
    return window - now.difference(list.first);
  }

  void fail(String key) => (_failures[key] ??= []).add(DateTime.now());
  void reset(String key) => _failures.remove(key);
}

final throttle = LoginThrottle(maxFailures: 3);

Future<Response> login(Request request) async {
  final Object? body;
  try {
    body = jsonDecode(await request.readAsString());
  } on FormatException {
    return jsonResponse(400, {'error': 'invalid JSON'});
  }
  if (body case {'username': String name, 'password': String password}) {
    final wait = throttle.retryAfter(name);
    if (wait != null) {
      return jsonResponse(429, {'error': 'too many attempts'},
          headers: {'retry-after': '${wait.inSeconds + 1}'});
    }

    final user = users[name];
    // Verify against a dummy hash for unknown users so that the response
    // time doesn't reveal which usernames exist.
    final ok = await verifyPassword(password, user?.passwordHash ?? dummyHash);
    if (user == null || !ok) {
      throttle.fail(name);
      return jsonResponse(401, {'error': 'invalid username or password'});
    }
    throttle.reset(name);

    if (needsRehash(user.passwordHash)) {
      user.passwordHash = await hashPassword(password);
    }

    final token = newToken();
    sessions[tokenKey(token)] =
        Session(user.name, DateTime.now().add(tokenLifetime));
    return jsonResponse(200, {
      'access_token': token,
      'token_type': 'Bearer',
      'expires_in': tokenLifetime.inSeconds,
    });
  }
  return jsonResponse(400, {'error': 'username and password are required'});
}

String? bearerToken(Request request) {
  final header = request.headers['authorization'];
  if (header == null || !header.toLowerCase().startsWith('bearer ')) return null;
  return header.substring(7).trim();
}

/// Rejects requests without a valid token; puts the User in request.context.
Middleware requireAuth() => (Handler inner) => (Request request) {
      final token = bearerToken(request);
      final session = token == null ? null : sessions[tokenKey(token)];
      if (session == null || DateTime.now().isAfter(session.expiresAt)) {
        if (session != null) sessions.remove(tokenKey(token!));
        return jsonResponse(401, {'error': 'not authenticated'},
            headers: {'www-authenticate': 'Bearer'});
      }
      final user = users[session.userName]!;
      return inner(request.change(context: {'user': user}));
    };

/// Must run after [requireAuth].
Middleware requireRole(String role) => (Handler inner) => (Request request) {
      final user = request.context['user'] as User;
      if (!user.roles.contains(role)) {
        return jsonResponse(403, {'error': 'requires role $role'});
      }
      return inner(request);
    };

Handler buildApp() {
  final protected = Router()
    ..get('/me', (Request r) {
      final user = r.context['user'] as User;
      return jsonResponse(200, {'name': user.name, 'roles': [...user.roles]});
    })
    ..post('/logout', (Request r) {
      sessions.remove(tokenKey(bearerToken(r)!));
      return Response(204);
    })
    ..get(
        '/admin/stats',
        const Pipeline()
            .addMiddleware(requireRole('admin'))
            .addHandler((Request r) =>
                jsonResponse(200, {'activeSessions': sessions.length})));

  final app = Router()
    ..post('/login', login)
    ..mount('/', const Pipeline().addMiddleware(requireAuth()).addHandler(protected.call));
  return app.call;
}

Future<void> main() async {
  dummyHash = await hashPassword('dummy password, never matches');
  users['alice'] = User('alice', await hashPassword('alice-pass'));
  users['bob'] =
      User('bob', await hashPassword('bob-pass'), roles: {'admin'});

  final server =
      await io.serve(buildApp(), InternetAddress.loopbackIPv4, 0);
  final base = 'http://localhost:${server.port}';
  print('listening on port ${server.port}');

  Future<String?> doLogin(String user, String pass) async {
    final r = await http.post(Uri.parse('$base/login'),
        body: jsonEncode({'username': user, 'password': pass}));
    print('POST /login $user/$pass -> ${r.statusCode} ${r.body}'
        '${r.headers['retry-after'] != null ? ' retry-after: ${r.headers['retry-after']}' : ''}');
    return r.statusCode == 200 ? jsonDecode(r.body)['access_token'] : null;
  }

  Future<void> call(String method, String path, [String? token]) async {
    final req = http.Request(method, Uri.parse('$base$path'));
    if (token != null) req.headers['authorization'] = 'Bearer $token';
    final r = await http.Response.fromStream(await req.send());
    print('$method $path -> ${r.statusCode} ${r.body}');
  }

  await call('GET', '/me');
  final alice = await doLogin('alice', 'alice-pass');
  await call('GET', '/me', alice);
  await call('GET', '/admin/stats', alice);
  final bob = await doLogin('bob', 'bob-pass');
  await call('GET', '/admin/stats', bob);
  await call('POST', '/logout', alice);
  await call('GET', '/me', alice);

  for (var i = 0; i < 4; i++) {
    await doLogin('alice', 'guess$i');
  }
  await doLogin('nobody', 'guess');

  await server.close();
}

Output (the port and tokens differ on every run):

listening on port 59930
GET /me -> 401 {"error":"not authenticated"}
POST /login alice/alice-pass -> 200 {"access_token":"uZcWSjSeucn33DqopAHNAP5kvF-tD8LPzNHa38pT68Q","token_type":"Bearer","expires_in":3600}
GET /me -> 200 {"name":"alice","roles":[]}
GET /admin/stats -> 403 {"error":"requires role admin"}
POST /login bob/bob-pass -> 200 {"access_token":"v5kS-YT27h-zoRRB9UYzgaeWW-otrbtIcNAvqDJ7GHs","token_type":"Bearer","expires_in":3600}
GET /admin/stats -> 200 {"activeSessions":2}
POST /logout -> 204
GET /me -> 401 {"error":"not authenticated"}
POST /login alice/guess0 -> 401 {"error":"invalid username or password"}
POST /login alice/guess1 -> 401 {"error":"invalid username or password"}
POST /login alice/guess2 -> 401 {"error":"invalid username or password"}
POST /login alice/guess3 -> 429 {"error":"too many attempts"} retry-after: 900
POST /login nobody/guess -> 401 {"error":"invalid username or password"}

How it fits together:

In production keep users and sessions in a database or Redis (see Redis) so that tokens survive restarts and work across several server processes, and delete expired sessions periodically.

Slowing down password guessing

LoginThrottle allows 3 failed attempts per username within 15 minutes (5 is a more typical production value), then answers 429 Too Many Requests with a Retry-After header. A real deployment also limits attempts per client IP address, since an attacker can try one common password against many usernames. These counters live in memory, so they are per process; with several server instances keep them in Redis.

Locking by username lets anyone lock someone else out by typing wrong passwords. Gentler alternatives are an increasing delay, or a CAPTCHA after a few failures instead of a block.

Tokens in browsers

For a browser app served from the same site as the API, an HttpOnly; Secure; SameSite=Lax session cookie is safer than a token kept in localStorage, because JavaScript (including injected scripts) can't read it. The login code stays the same: instead of returning the token in JSON, send it in Set-Cookie, and have requireAuth() read it from the Cookie header. The Sessions and Cookies articles show how. Browsers send cookies automatically, so state-changing requests then also need CSRF protection; SameSite=Lax covers most cases.

A client that handles tokens

On the client side you don't want every call to deal with the Authorization header and expired tokens. http.BaseClient lets you wrap another client and change every request in one place:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:http/testing.dart';

/// Adds `Authorization: Bearer` to every request. On a 401 it obtains a new
/// token once and repeats the request.
class AuthClient extends http.BaseClient {
  AuthClient(this._inner, this._fetchToken);

  final http.Client _inner;
  final Future<String> Function(http.Client) _fetchToken;
  Future<String>? _token; // shared by concurrent requests

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    // A request body is a stream that can be read only once, so buffer
    // non-streamed requests to be able to send them a second time.
    final copy = request is http.Request ? _copy(request) : null;

    final token = await (_token ?? _newToken());
    request.headers['authorization'] = 'Bearer $token';
    final response = await _inner.send(request);
    if (response.statusCode != 401 || copy == null) return response;

    await response.stream.drain<void>();
    // Another request may have refreshed the token already.
    final current = await (_token ?? _newToken());
    final fresh = current == token ? await _newToken() : current;
    copy.headers['authorization'] = 'Bearer $fresh';
    return _inner.send(copy);
  }

  Future<String> _newToken() {
    final future = _fetchToken(_inner);
    _token = future;
    // Don't cache a failed login: the next request will try again.
    future.then((_) {}, onError: (Object _) {
      if (identical(_token, future)) _token = null;
    });
    return future;
  }

  static http.Request _copy(http.Request r) => http.Request(r.method, r.url)
    ..headers.addAll(r.headers)
    ..bodyBytes = r.bodyBytes
    ..followRedirects = r.followRedirects;

  @override
  void close() => _inner.close();
}

Future<void> main() async {
  // A fake API: each token works for two requests.
  var issued = 0;
  final uses = <String, int>{};
  final api = MockClient((request) async {
    if (request.url.path == '/login') {
      final token = 'token-${++issued}';
      print('  server: issued $token');
      return http.Response(jsonEncode({'access_token': token}), 200);
    }
    final token = request.headers['authorization']?.substring(7) ?? '';
    final n = uses[token] = (uses[token] ?? 0) + 1;
    if (!token.startsWith('token-') || n > 2) {
      return http.Response('{"error":"not authenticated"}', 401);
    }
    return http.Response('{"echo":${jsonEncode(request.body)}}', 200);
  });

  Future<String> login(http.Client client) async {
    final r = await client.post(Uri.parse('https://api.example.com/login'),
        body: jsonEncode({'username': 'alice', 'password': 'alice-pass'}));
    if (r.statusCode != 200) throw Exception('login failed: ${r.body}');
    return jsonDecode(r.body)['access_token'] as String;
  }

  final client = AuthClient(api, login);
  for (var i = 1; i <= 5; i++) {
    final r = await client.post(Uri.parse('https://api.example.com/notes'),
        body: 'note $i');
    print('request $i -> ${r.statusCode} ${r.body}');
  }
  client.close();
}

Output:

  server: issued token-1
request 1 -> 200 {"echo":"note 1"}
request 2 -> 200 {"echo":"note 2"}
  server: issued token-2
request 3 -> 200 {"echo":"note 3"}
request 4 -> 200 {"echo":"note 4"}
  server: issued token-3
request 5 -> 200 {"echo":"note 5"}

Notes:

API keys

API keys are long-lived credentials for programs: a CI job, a backend calling your API, a user's script. They work like the bearer tokens above (random, stored hashed, looked up on each request), with a few conventions of their own:

import 'dart:convert';
import 'dart:math';

import 'package:crypto/crypto.dart';

class ApiKeyRecord {
  ApiKeyRecord(this.owner, this.prefix, this.created);
  final String owner;
  final String prefix; // shown in the UI so users can tell keys apart
  final DateTime created;
}

// sha256(key) -> record. The full key is never stored.
final apiKeys = <String, ApiKeyRecord>{};

String _hash(String key) => sha256.convert(utf8.encode(key)).toString();

String createApiKey(String owner) {
  final rng = Random.secure();
  final secret = base64Url
      .encode(List<int>.generate(24, (_) => rng.nextInt(256)));
  final key = 'myapp_$secret'; // a recognizable prefix helps secret scanners
  apiKeys[_hash(key)] =
      ApiKeyRecord(owner, key.substring(0, 12), DateTime.now());
  return key; // show it to the user once
}

ApiKeyRecord? checkApiKey(String? key) =>
    key == null ? null : apiKeys[_hash(key)];

void main() {
  final key = createApiKey('alice');
  print('new key: $key');
  print('stored:  ${apiKeys.keys.single}');

  final record = checkApiKey(key);
  print('valid:   ${record?.owner} (${record?.prefix}...)');
  print('invalid: ${checkApiKey('myapp_not-a-real-key')?.owner}');

  // Revoking is just deleting the record.
  apiKeys.removeWhere((_, r) => r.owner == 'alice');
  print('revoked: ${checkApiKey(key)?.owner}');
}

Output:

new key: myapp_EvOFPn9usRHqFdKz0teLN-BuSXBRwOHr
stored:  b83661b82c13689f4d11a4df63986f298238fefb89a050d0b2fcaeb69cb2fb47
valid:   alice (myapp_EvOFPn...)
invalid: null
revoked: null

Two-factor authentication with TOTP

Authenticator apps (Google Authenticator, 1Password, Authy...) generate 6-digit codes with the TOTP algorithm (RFC 6238). The server and the app share a random secret. Every 30 seconds both compute HMAC-SHA1(secret, current time / 30) and turn the result into a short number. With package:crypto it takes a few dozen lines:

import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';

const _b32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

String base32Encode(List<int> bytes) {
  final out = StringBuffer();
  var buffer = 0, bits = 0;
  for (final b in bytes) {
    buffer = (buffer << 8) | b;
    bits += 8;
    while (bits >= 5) {
      out.write(_b32[(buffer >> (bits - 5)) & 31]);
      bits -= 5;
    }
  }
  if (bits > 0) out.write(_b32[(buffer << (5 - bits)) & 31]);
  return out.toString();
}

List<int> base32Decode(String s) {
  final out = <int>[];
  var buffer = 0, bits = 0;
  for (final ch in s.toUpperCase().replaceAll(RegExp(r'[\s=]'), '').split('')) {
    final v = _b32.indexOf(ch);
    if (v < 0) throw FormatException('invalid base32 character', s);
    buffer = ((buffer << 5) | v) & 0xFFFF;
    bits += 5;
    if (bits >= 8) {
      out.add((buffer >> (bits - 8)) & 0xFF);
      bits -= 8;
    }
  }
  return out;
}

/// RFC 6238 time-based one-time password (HMAC-SHA1, 30 s steps).
String totp(List<int> secret, DateTime time, {int digits = 6, int step = 30}) {
  final counter = time.millisecondsSinceEpoch ~/ 1000 ~/ step;
  final msg = ByteData(8)..setInt64(0, counter);
  final mac = Hmac(sha1, secret).convert(msg.buffer.asUint8List()).bytes;
  final offset = mac.last & 0x0f; // RFC 4226 dynamic truncation
  final code = ((mac[offset] & 0x7f) << 24) |
      (mac[offset + 1] << 16) |
      (mac[offset + 2] << 8) |
      mac[offset + 3];
  return (code % pow(10, digits).toInt()).toString().padLeft(digits, '0');
}

/// Accepts the current code and the ones just before and after it, to allow
/// for clock drift between the server and the phone.
bool verifyTotp(List<int> secret, String code, {DateTime? now}) {
  now ??= DateTime.now();
  for (final drift in [0, -30, 30]) {
    final expected = totp(secret, now.add(Duration(seconds: drift)));
    if (_constantTimeEquals(expected, code)) return true;
  }
  return false;
}

bool _constantTimeEquals(String a, String b) {
  if (a.length != b.length) return false;
  var diff = 0;
  for (var i = 0; i < a.length; i++) {
    diff |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
  }
  return diff == 0;
}

void main() {
  // RFC 6238 test vectors (8 digits, SHA-1).
  final rfcSecret = ascii.encode('12345678901234567890');
  for (final t in [59, 1111111109, 1234567890, 2000000000]) {
    final time = DateTime.fromMillisecondsSinceEpoch(t * 1000, isUtc: true);
    print('$t -> ${totp(rfcSecret, time, digits: 8)}');
  }

  // Enrolling a user: generate a secret and show it as a QR code of this URI.
  final rng = Random.secure();
  final secret = List<int>.generate(20, (_) => rng.nextInt(256));
  final encoded = base32Encode(secret);
  final uri = Uri(scheme: 'otpauth', host: 'totp', path: '/MyApp:alice',
      queryParameters: {'secret': encoded, 'issuer': 'MyApp'});
  print(uri);
  print('round trip ok: ${base32Encode(base32Decode(encoded)) == encoded}');

  final now = DateTime.now();
  final code = totp(secret, now);
  print('code now: $code, valid: ${verifyTotp(secret, code, now: now)}');
  final old = totp(secret, now.subtract(const Duration(minutes: 2)));
  print('2-minute-old code valid: ${verifyTotp(secret, old, now: now)}');
}

Output (the secret and the current code differ on every run):

59 -> 94287082
1111111109 -> 07081804
1234567890 -> 89005924
2000000000 -> 69279037
otpauth://totp/MyApp:alice?secret=QJHHJT5ZSYCEVBLR4LPUK74J53AMG4TS&issuer=MyApp
round trip ok: true
code now: 239671, valid: true
2-minute-old code valid: false

The first four lines match the test vectors in RFC 6238, appendix B.

Enrolling a user:

  1. Generate a 20-byte secret with Random.secure() and store it with the user, encrypted if you can (see Cryptography). Unlike a password it can't be hashed, because the server needs the secret itself to compute codes.
  2. Show the otpauth:// URI as a QR code. Most apps also accept the Base32 secret typed in by hand.
  3. Ask the user to enter a code, and turn on 2FA only if it verifies. This proves the app was set up correctly.
  4. Generate a handful of single-use recovery codes, show them once, and store their hashes.

At login, after the password check succeeds, don't issue the real token yet. Return a short-lived "password OK, waiting for a code" state and issue the token only after verifyTotp() succeeds. Throttle code attempts the same way as password attempts: there are only a million 6-digit codes. To stop an observed code from being reused, remember the last accepted time step per user and reject codes from that step or earlier.

ByteData.setInt64 isn't supported when compiling to JavaScript. That doesn't matter here, since TOTP verification belongs on the server.

Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents