OAuth

suggest change

OAuth 2.0 lets an application act on a user's behalf (or on its own behalf) without ever seeing the user's password. The app sends the user to an authorization server (Google, GitHub, Auth0, Keycloak, your own), the user signs in there, and the app gets back an access token. The app then sends that token to an API (the resource server) in an Authorization: Bearer <token> header.

Which flow you use depends on who the client is:

Flow (grant type) Use it for
Authorization code + PKCE Anything a user logs into: CLI tools, desktop, mobile (Flutter), web apps
Client credentials Server-to-server jobs with no user involved
Refresh token Getting a new access token when the old one expires
Device code TVs and headless devices (user signs in on another device)

The implicit flow and the resource owner password flow are deprecated by the OAuth 2.1 draft and current security best practice; don't use them in new code.

In Dart the standard package is oauth2 from the Dart team. It implements the authorization code flow with PKCE, client credentials and automatic token refresh, and its Client is a drop-in http.Client:

dependencies:
  oauth2: ^2.0.5
  http: ^1.6.0
  crypto: ^3.0.7

The examples below were run with Dart 3.13 against a small local authorization server, shown at the end of the article, listening on http://localhost:9090. Tokens are random, so yours will differ.

The authorization code flow with PKCE

App                       Browser                 Authorization server        API
 | 1. create verifier,       |                              |                   |
 |    challenge, state       |                              |                   |
 | 2. open /authorize?...    |                              |                   |
 | ------------------------> | --------------------------> | 3. user logs in,   |
 |                           |                              |    approves        |
 |                           | <-- 302 redirect_uri?code=..&state=..            |
 | 4. callback with code     |                              |                   |
 | <------------------------ |                              |                   |
 | 5. POST /token (code + code_verifier) ----------------> |                   |
 | <------------------ access_token, refresh_token -------- |                   |
 | 6. GET /api (Authorization: Bearer ...) -------------------------------------> |

Two random values protect the flow:

Generating PKCE values by hand

oauth2 does this for you, but it's worth seeing how little is involved. The verifier is 43 to 128 characters from the unreserved URL alphabet; 32 secure random bytes in unpadded base64url gives 43:

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

import 'package:crypto/crypto.dart';

final _random = Random.secure();

/// 32 random bytes -> 43 characters of unpadded base64url.
String randomUrlSafe([int bytes = 32]) => base64Url
    .encode(List<int>.generate(bytes, (_) => _random.nextInt(256)))
    .replaceAll('=', '');

String codeChallenge(String verifier) => base64Url
    .encode(sha256.convert(ascii.encode(verifier)).bytes)
    .replaceAll('=', '');

void main() {
  // Test vector from RFC 7636, Appendix B.
  const rfcVerifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
  print(codeChallenge(rfcVerifier));

  final verifier = randomUrlSafe();
  final state = randomUrlSafe(16);
  print('verifier: ${verifier.length} chars');

  final authUrl = Uri.https('auth.example.com', '/authorize', {
    'response_type': 'code',
    'client_id': 'cli-app',
    'redirect_uri': 'http://127.0.0.1:8085/callback',
    'scope': 'openid profile read:orders',
    'state': state,
    'code_challenge': codeChallenge(verifier),
    'code_challenge_method': 'S256',
  });
  print(authUrl.queryParameters.keys.join(', '));
  print(authUrl);
}

Output:

E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
verifier: 43 chars
response_type, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method
https://auth.example.com/authorize?response_type=code&client_id=cli-app&redirect_uri=http%3A%2F%2F127.0.0.1%3A8085%2Fcallback&scope=openid+profile+read%3Aorders&state=pdm97hdvR4Yus7zs3VX91g&code_challenge=BdBUj91lHxEL7AF9q6zBSsrWAe33QpA5bqDvY7avGU4&code_challenge_method=S256

The first line matches the challenge in the RFC, so the encoding is right. Always use Random.secure() for these values, never Random() (see Random numbers), and always use the S256 method, not plain.

Logging in from a command-line app

A CLI or desktop app receives the redirect on a loopback HTTP server (RFC 8252). Binding to port 0 lets the OS pick a free port; register http://127.0.0.1/callback with the provider (most allow any port for loopback redirects).

The complete program below opens the browser, waits for the callback, exchanges the code, saves the credentials to a file and calls an API. On the next run it reuses the saved credentials instead of logging in again:

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

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

final authServer = Uri.parse('http://localhost:9090');
final authorizationEndpoint = authServer.resolve('/authorize');
final tokenEndpoint = authServer.resolve('/token');
const clientId = 'cli-app';
final credentialsFile = File('credentials.json');

String randomState() => base64Url
    .encode(List.generate(16, (_) => Random.secure().nextInt(256)))
    .replaceAll('=', '');

/// Opens [url] in the user's default browser.
Future<void> openBrowser(Uri url) async {
  if (Platform.isWindows) {
    await Process.run('rundll32', ['url.dll,FileProtocolHandler', '$url']);
  } else if (Platform.isMacOS) {
    await Process.run('open', ['$url']);
  } else {
    await Process.run('xdg-open', ['$url']);
  }
}

Future<oauth2.Client> login({required bool simulateBrowser}) async {
  // Port 0 lets the OS pick a free port for the loopback redirect.
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  final redirectUrl = Uri.parse('http://127.0.0.1:${server.port}/callback');

  final grant = oauth2.AuthorizationCodeGrant(
    clientId,
    authorizationEndpoint,
    tokenEndpoint,
  );
  final authUrl = grant.getAuthorizationUrl(
    redirectUrl,
    scopes: ['profile', 'read:orders'],
    state: randomState(),
  );

  // Wait for the browser to hit /callback, with a timeout.
  final callback = server
      .firstWhere((req) => req.uri.path == '/callback')
      .timeout(const Duration(minutes: 5));

  if (simulateBrowser) {
    // Act as the browser: follow the redirect to our loopback server.
    unawaited(http.get(authUrl));
  } else {
    print('Opening $authUrl');
    await openBrowser(authUrl);
  }

  final request = await callback;
  request.response
    ..headers.contentType = ContentType.html
    ..write('<h1>Signed in. You can close this tab.</h1>');
  await request.response.close();
  await server.close(force: true);

  // Checks state, exchanges the code (with the PKCE verifier) for tokens.
  return grant.handleAuthorizationResponse(request.uri.queryParameters);
}

Future<oauth2.Client> getClient() async {
  if (await credentialsFile.exists()) {
    final credentials =
        oauth2.Credentials.fromJson(await credentialsFile.readAsString());
    print('Loaded saved credentials');
    return oauth2.Client(credentials, identifier: clientId);
  }
  final client = await login(simulateBrowser: true);
  await credentialsFile.writeAsString(client.credentials.toJson());
  print('Saved credentials to ${credentialsFile.path}');
  return client;
}

Future<void> main() async {
  final client = await getClient();
  final creds = client.credentials;
  print('access token: ${creds.accessToken.substring(0, 6)}...');
  print('refresh token present: ${creds.refreshToken != null}');
  print('scopes: ${creds.scopes}');
  print('expires: ${creds.expiration!.difference(DateTime.now()).inMinutes} min');

  final res = await client.get(authServer.resolve('/api/me'));
  print('${res.statusCode} ${res.body}');
  client.close();
}

Output of the first run, then the second:

Saved credentials to credentials.json
access token: v5q58p...
refresh token present: true
scopes: [profile, read:orders]
expires: 59 min
200 {"user":"alice","scope":"profile read:orders"}
Loaded saved credentials
access token: v5q58p...
refresh token present: true
scopes: [profile, read:orders]
expires: 59 min
200 {"user":"alice","scope":"profile read:orders"}

To make the example runnable without a person clicking through a login page, simulateBrowser: true makes the app play the browser: http.get follows the authorization server's 302 redirect to the loopback server. In a real app, pass false so the system browser opens and the user logs in there. Never collect the user's password in your own UI; the point of OAuth is that only the authorization server sees it.

Some things to know about AuthorizationCodeGrant:

The saved file is plain JSON:

{"accessToken":"v5q58pTOMmQy1pytcf1XumMvwBWMjTBG","refreshToken":"VJlCOoK3qKd7kEI6aaiGQd0eKUToPwyc","idToken":null,"tokenEndpoint":"http://localhost:9090/token","scopes":["profile","read:orders"],"expiration":1792267236683}

A refresh token is as sensitive as a password. On desktop, store it with restrictive file permissions or in the OS keychain; in Flutter use flutter_secure_storage.

Handling errors in the callback

handleAuthorizationResponse verifies state and turns OAuth error responses into exceptions. A wrong state throws a FormatException; an error parameter from the server, or a failed token exchange, throws AuthorizationException:

import 'package:oauth2/oauth2.dart' as oauth2;

Future<void> main() async {
  Future<void> attempt(Map<String, String> callbackParams) async {
    final grant = oauth2.AuthorizationCodeGrant(
      'cli-app',
      Uri.parse('http://localhost:9090/authorize'),
      Uri.parse('http://localhost:9090/token'),
    );
    grant.getAuthorizationUrl(Uri.parse('http://127.0.0.1:8085/callback'),
        state: 'expected-state');
    try {
      await grant.handleAuthorizationResponse(callbackParams);
    } on FormatException catch (e) {
      print('FormatException: ${e.message}');
    } on oauth2.AuthorizationException catch (e) {
      print('AuthorizationException: ${e.error} (${e.description})');
    }
  }

  // An attacker-crafted callback with a different state.
  await attempt({'code': 'abc', 'state': 'attacker-state'});
  // The user clicked "Deny" on the consent screen.
  await attempt({
    'error': 'access_denied',
    'error_description': 'The user denied the request',
    'state': 'expected-state',
  });
  // A code that was never issued.
  await attempt({'code': 'stolen-code', 'state': 'expected-state'});
}

Output:

FormatException: Invalid OAuth response for "http://localhost:9090/authorize": parameter "state" expected to be "expected-state", was "attacker-state".
AuthorizationException: access_denied (The user denied the request)
AuthorizationException: invalid_grant (unknown or used code)

access_denied is a normal outcome, not a bug: show the user a message and let them try again.

Refreshing tokens

Access tokens are short-lived (minutes to hours). When oauth2.Client is about to send a request with an expired token and it has a refresh token, it calls the token endpoint with grant_type=refresh_token first. Many servers rotate refresh tokens: each refresh returns a new refresh token and the old one stops working. So persist the new credentials every time, using onCredentialsRefreshed:

import 'dart:io';

import 'package:oauth2/oauth2.dart' as oauth2;

final api = Uri.parse('http://localhost:9090/api/me');
final credentialsFile = File('credentials.json');

Future<void> main() async {
  final saved =
      oauth2.Credentials.fromJson(await credentialsFile.readAsString());

  // Pretend the access token expired an hour ago.
  final expired = oauth2.Credentials(
    saved.accessToken,
    refreshToken: saved.refreshToken,
    tokenEndpoint: saved.tokenEndpoint,
    scopes: saved.scopes,
    expiration: DateTime.now().subtract(const Duration(hours: 1)),
  );
  print('expired: ${expired.isExpired}, can refresh: ${expired.canRefresh}');

  final client = oauth2.Client(
    expired,
    identifier: 'cli-app',
    onCredentialsRefreshed: (creds) async {
      // Refresh tokens may rotate: always persist the new pair.
      await credentialsFile.writeAsString(creds.toJson());
      print('refreshed, new token ${creds.accessToken.substring(0, 6)}...');
    },
  );

  // The client notices the expiry and refreshes before sending.
  final res = await client.get(api);
  print('${res.statusCode} ${res.body}');
  client.close();

  // The old refresh token was rotated away by the server.
  try {
    await expired.refresh(identifier: 'cli-app');
  } on oauth2.AuthorizationException catch (e) {
    print('error: ${e.error}, ${e.description}');
  }
}

Output:

expired: true, can refresh: true
refreshed, new token n_vUnl...
200 {"user":"alice","scope":"profile read:orders"}
error: invalid_grant, bad refresh token

When the package computes expiration from the server's expires_in, it subtracts 10 seconds, so a request doesn't race the deadline. If a token is expired and can't be refreshed, Client throws ExpirationException. An invalid_grant on refresh means the session is over (the user revoked access, or the refresh token expired or was reused): delete the saved credentials and log in again.

A server can also revoke a token before it expires. The API then answers 401 with a WWW-Authenticate: Bearer error="invalid_token" header, and oauth2.Client turns that into an exception instead of retrying:

import 'package:oauth2/oauth2.dart' as oauth2;

Future<void> main() async {
  final client = oauth2.Client(oauth2.Credentials('revoked-token'));
  try {
    await client.get(Uri.parse('http://localhost:9090/api/me'));
  } on oauth2.AuthorizationException catch (e) {
    print('error: ${e.error}');
  }
  client.close();
}

Output:

error: invalid_token

Catch it, call client.refreshCredentials() if the client can refresh, and retry the request once; if that fails too, log in again.

Client credentials: machine-to-machine

A backend job with no user calls the token endpoint with its own client ID and secret. There's no browser, redirect or refresh token; when the token expires you just request a new one:

import 'dart:io';

import 'package:oauth2/oauth2.dart' as oauth2;

final tokenEndpoint = Uri.parse('http://localhost:9090/token');
final api = Uri.parse('http://localhost:9090/api/me');

Future<void> main() async {
  final id = Platform.environment['OAUTH_CLIENT_ID'] ?? 'report-job';
  final secret = Platform.environment['OAUTH_CLIENT_SECRET'] ?? 's3cr3t';

  final client = await oauth2.clientCredentialsGrant(
    tokenEndpoint,
    id,
    secret,
    scopes: ['reports:write'],
  );
  print('refresh token: ${client.credentials.refreshToken}');
  final res = await client.get(api);
  print('${res.statusCode} ${res.body}');
  client.close();

  try {
    await oauth2.clientCredentialsGrant(tokenEndpoint, id, 'wrong');
  } on oauth2.AuthorizationException catch (e) {
    print('error: ${e.error}');
  }
}

Output:

refresh token: null
200 {"user":"alice","scope":"reports:write"}
error: invalid_client

Load the secret from the environment or a secrets manager, never from source code. And never put a client secret in a Flutter or web app: anything shipped to users can be extracted. Those apps are public clients and use the authorization code flow with PKCE.

Talking to the token endpoint with plain http

The token endpoint is just a form POST that returns JSON, so you can call it without the oauth2 package. This is handy for providers with quirks, or for grants the package doesn't cover, such as the device code flow:

import 'dart:convert';

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

class TokenResponse {
  final String accessToken;
  final String? refreshToken;
  final DateTime expiresAt;
  final String scope;

  TokenResponse.fromJson(Map<String, dynamic> j)
      : accessToken = j['access_token'] as String,
        refreshToken = j['refresh_token'] as String?,
        expiresAt = DateTime.now()
            .add(Duration(seconds: (j['expires_in'] as num?)?.toInt() ?? 3600)),
        scope = j['scope'] as String? ?? '';
}

class OAuthException implements Exception {
  final String error;
  final String? description;
  OAuthException(this.error, this.description);
  @override
  String toString() => 'OAuthException($error: $description)';
}

Future<TokenResponse> requestToken(
  Uri tokenEndpoint,
  Map<String, String> form, {
  required String clientId,
  String? clientSecret,
}) async {
  final headers = {'Accept': 'application/json'};
  if (clientSecret != null) {
    final pair = '${Uri.encodeComponent(clientId)}:'
        '${Uri.encodeComponent(clientSecret)}';
    headers['Authorization'] = 'Basic ${base64.encode(utf8.encode(pair))}';
  } else {
    form = {...form, 'client_id': clientId};
  }
  // A Map body is sent as application/x-www-form-urlencoded.
  final res = await http.post(tokenEndpoint, headers: headers, body: form);
  final body = jsonDecode(res.body) as Map<String, dynamic>;
  if (res.statusCode != 200) {
    throw OAuthException(
        body['error'] as String, body['error_description'] as String?);
  }
  return TokenResponse.fromJson(body);
}

Future<void> main() async {
  final tokenEndpoint = Uri.parse('http://localhost:9090/token');

  final t = await requestToken(
    tokenEndpoint,
    {'grant_type': 'client_credentials', 'scope': 'reports:read'},
    clientId: 'report-job',
    clientSecret: 's3cr3t',
  );
  print('scope=${t.scope}, expires in '
      '${t.expiresAt.difference(DateTime.now()).inMinutes} min');

  final me = await http.get(Uri.parse('http://localhost:9090/api/me'),
      headers: {'Authorization': 'Bearer ${t.accessToken}'});
  print('${me.statusCode} ${me.body}');

  final bad = await http.get(Uri.parse('http://localhost:9090/api/me'),
      headers: {'Authorization': 'Bearer forged'});
  print('${bad.statusCode} ${bad.headers['www-authenticate']}');

  try {
    await requestToken(
      tokenEndpoint,
      {'grant_type': 'refresh_token', 'refresh_token': 'nope'},
      clientId: 'cli-app',
    );
  } on OAuthException catch (e) {
    print(e);
  }
}

Output:

scope=reports:read, expires in 59 min
200 {"user":"alice","scope":"reports:read"}
401 Bearer error="invalid_token"
OAuthException(invalid_grant: bad refresh token)

Per RFC 6749, errors from the token endpoint are a 400 (or 401) with a JSON body containing error and optionally error_description. The client ID and secret in the Basic header must be form-URL-encoded before Base64 encoding, which is what Uri.encodeComponent does here (see Base64 and hex encoding).

A minimal authorization server for tests

This Shelf server implements just enough of OAuth 2.0 to run all the examples above: /authorize (which approves immediately instead of showing a login page), /token with the authorization code (PKCE required), refresh token (with rotation) and client credentials grants, and a protected /api/me. It's useful for integration tests of your client code, and it shows what the server side checks. Don't use it in production; use a real identity provider or a maintained server such as Keycloak, Ory Hydra or Zitadel.

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

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

const clients = {
  'cli-app': null, // public client: no secret, must use PKCE
  'report-job': 's3cr3t', // confidential client
};

final _rng = Random.secure();
String newToken() => base64Url
    .encode(List.generate(24, (_) => _rng.nextInt(256)))
    .replaceAll('=', '');

String s256(String verifier) => base64Url
    .encode(sha256.convert(ascii.encode(verifier)).bytes)
    .replaceAll('=', '');

typedef PendingCode = ({
  String clientId,
  String redirectUri,
  String challenge,
  String scope,
});

final codes = <String, PendingCode>{};
final accessTokens = <String, String>{}; // access token -> scope
final refreshTokens = <String, String>{}; // refresh token -> scope

Response json(Object body, [int status = 200]) => Response(status,
    body: jsonEncode(body), headers: {'content-type': 'application/json'});

Response tokenError(String error, [String? description]) =>
    json({'error': error, 'error_description': ?description}, 400);

Map<String, Object> issueTokens(String scope, {bool refresh = true}) {
  final access = newToken();
  accessTokens[access] = scope;
  final body = <String, Object>{
    'access_token': access,
    'token_type': 'Bearer',
    'expires_in': 3600,
    'scope': scope,
  };
  if (refresh) {
    final refreshToken = newToken();
    refreshTokens[refreshToken] = scope;
    body['refresh_token'] = refreshToken;
  }
  return body;
}

Future<void> main(List<String> args) async {
  final app = Router();

  // A real server shows a login and consent page here; we approve at once.
  app.get('/authorize', (Request req) {
    final q = req.url.queryParameters;
    if (!clients.containsKey(q['client_id']) || q['response_type'] != 'code') {
      return Response.badRequest(body: 'invalid request');
    }
    if (q['code_challenge_method'] != 'S256') {
      return Response.badRequest(body: 'PKCE with S256 is required');
    }
    final code = newToken();
    codes[code] = (
      clientId: q['client_id']!,
      redirectUri: q['redirect_uri']!,
      challenge: q['code_challenge']!,
      scope: q['scope'] ?? '',
    );
    final redirect = Uri.parse(q['redirect_uri']!).replace(queryParameters: {
      'code': code,
      'state': ?q['state'],
    });
    return Response.found(redirect);
  });

  app.post('/token', (Request req) async {
    final form = Uri.splitQueryString(await req.readAsString());
    // Client authentication: HTTP Basic header or client_id in the body.
    var clientId = form['client_id'];
    var secret = form['client_secret'];
    final auth = req.headers['authorization'];
    if (auth != null && auth.startsWith('Basic ')) {
      final pair = utf8.decode(base64.decode(auth.substring(6))).split(':');
      clientId = Uri.decodeComponent(pair[0]);
      secret = Uri.decodeComponent(pair[1]);
    }
    if (!clients.containsKey(clientId)) return tokenError('invalid_client');
    final expected = clients[clientId];
    if (expected != null && expected != secret) {
      return tokenError('invalid_client');
    }

    switch (form['grant_type']) {
      case 'authorization_code':
        final pending = codes.remove(form['code']); // codes are single-use
        if (pending == null || pending.clientId != clientId) {
          return tokenError('invalid_grant', 'unknown or used code');
        }
        if (pending.redirectUri != form['redirect_uri']) {
          return tokenError('invalid_grant', 'redirect_uri mismatch');
        }
        if (s256(form['code_verifier'] ?? '') != pending.challenge) {
          return tokenError('invalid_grant', 'PKCE verification failed');
        }
        return json(issueTokens(pending.scope));
      case 'refresh_token':
        // Rotation: an old refresh token stops working once used.
        final scope = refreshTokens.remove(form['refresh_token']);
        if (scope == null) return tokenError('invalid_grant', 'bad refresh token');
        return json(issueTokens(scope));
      case 'client_credentials':
        if (expected == null) return tokenError('unauthorized_client');
        return json(issueTokens(form['scope'] ?? '', refresh: false));
      default:
        return tokenError('unsupported_grant_type');
    }
  });

  // A protected resource.
  app.get('/api/me', (Request req) {
    final auth = req.headers['authorization'] ?? '';
    final token = auth.startsWith('Bearer ') ? auth.substring(7) : '';
    final scope = accessTokens[token];
    if (scope == null) {
      return Response(401,
          headers: {'www-authenticate': 'Bearer error="invalid_token"'});
    }
    return json({'user': 'alice', 'scope': scope});
  });

  final port = args.isEmpty ? 9090 : int.parse(args.first);
  final server = await io.serve(app.call, 'localhost', port);
  print('Authorization server on http://localhost:${server.port}');
}

It needs shelf: ^1.4.3, shelf_router: ^1.1.5 and crypto in pubspec.yaml. 'state': ?q['state'] and 'error_description': ?description use null-aware map elements (Dart 3.8+): the entry is left out when the value is null.

Real servers keep tokens in a database or Redis with an expiry, compare secrets in constant time, and usually issue access tokens as signed JWTs so an API can validate them locally (check signature, iss, aud, exp and scope) without calling the authorization server. Opaque tokens like the ones above are validated through the token introspection endpoint (RFC 7662) instead.

OpenID Connect and Flutter

OAuth 2.0 is about authorization: the access token says what the app may do, not who the user is. OpenID Connect (OIDC) adds identity on top: request the openid scope and the token response also contains an id_token, a JWT with the user's ID (sub), and with email or profile scopes, more claims. oauth2.Credentials.idToken holds it. Validate it (signature from the provider's JWKS, iss, aud equal to your client ID, exp, and nonce if you sent one) before trusting it. OIDC providers publish their endpoints at /.well-known/openid-configuration, so you can fetch the authorization and token URLs instead of hard-coding them.

In Flutter, don't use a WebView for login: providers like Google block it, and the app could read the user's password. Use the system browser via flutter_appauth (AppAuth for iOS and Android) or flutter_web_auth_2, with a custom URL scheme or app link as the redirect URI, and store tokens with flutter_secure_storage.

Checklist

Feedback about page:

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



Table Of Contents