authenticateWithAuthorizationCode function

Future<Credential> authenticateWithAuthorizationCode(
  1. Client client,
  2. String code,
  3. String state,
  4. String sessionState,
  5. String iss,
)

Implementation

Future<Credential> authenticateWithAuthorizationCode(
  Client client,
  String code,
  String state,
  String sessionState,
  String iss,
) async {
  Map<String, String> queryParameters = {
    'grant_type': 'authorization_code',
    'client_id': client.clientId,
    'code': code,
    'redirect_uri': makeReturnUrl(),
    'state': state,
    'session_state': sessionState,
    'iss': iss,
    'client_secret': client.clientSecret!,
  };

  BaseOptions options = BaseOptions(
    baseUrl: makeReturnUrl(),
    headers: {
      "Accept": "application/json",
      'Content-type': 'application/x-www-form-urlencoded',
    },
  );

  var dio = Dio(options);
  var data = queryParameters.entries
      .map((e) =>
          '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
      .join('&');

  try {
    /*final response = await dio.post(
      'https://corsproxy.io/?${Uri.encodeComponent(client.issuer.metadata.tokenEndpoint.toString())}',
      data: data,
    );*/
    final response = await dio.postUri(
      client.issuer.metadata.tokenEndpoint!,
      data: data,
    );

    if (response.statusCode != 200) {
      throw Exception('Failed to get token: ${response.data}');
    }

    var token = TokenResponse.fromJson(response.data);

    return client.createCredential(
      accessToken: token.accessToken,
      refreshToken: token.refreshToken,
      expiresAt: token.expiresAt,
      expiresIn: token.expiresIn,
    );
  } catch (e) {
    throw Exception('Failed to get token: $e');
  }
}