Getting an Access Token from Auth0 in Flutter
Auth0 manages two concepts for representing APIs and Applications (or consumers for those APIs). When an access token is negotiated, the client application must present a pair of Client ID and Secret for authentication, and also the identifier of the API is trying to call. Auth0 will use the API identifier to include it as audience in the Access Token (JWT) and also apply Role Based Controls (if that option is set for your application).
Before doing anything, you must first register the API and the Application (or Client) in the Auth0 dashboard.
For an API, the most important setting is the "Identifier".
For an Application, it is the Domain, Client ID and Client Secret.
You can use this article as starting point to configure the development environment for Flutter and the authentication libraries you will need.
The library to be used from Flutter is "flutter_appauth". You can add it as a dependency under your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
http: ^0.12.1
flutter_appauth: ^0.9.1
....
After that, you can simply import the library and use it.
import 'package:flutter_appauth/flutter_appauth.dart';
final FlutterAppAuth appAuth = FlutterAppAuth();
const AUTH0_REDIRECT_URI = '<scheme>://login-callback';
The Redirect URI configuration in the application is discussed in the article mentioned above.
Finally, you can get an access token using the code below.
Future<AuthorizationTokenResponse> getApiAccessToken() async {
final AuthorizationTokenResponse result =
await appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest("<CLIENT_ID>", AUTH0_REDIRECT_URI,
issuer: 'https://${<AUTH0_DOMAIN>}',
additionalParameters: {"audience": <API_AUDIENCE>}),
);
return result;
}
CLIENT_ID is the Client Id assigned by Auth0 to your application when it was created
AUTH0_DOMAIN is the Domain assigned to your Tenant in Auth0 (you can also get it from the Application settings)
API_AUDIENCE is the Identifier of the API to be called (the one it was defined when the API was registered in the Dashboard).