getTokenWithAuthCodeFlow method

Future<AccessTokenResponse> getTokenWithAuthCodeFlow({
  1. required String clientId,
  2. List<String>? scopes,
  3. String? clientSecret,
  4. bool enablePKCE = true,
  5. bool enableState = true,
  6. String? state,
  7. String? codeVerifier,
  8. Function? afterAuthorizationCodeCb,
  9. Map<String, dynamic>? authCodeParams,
  10. Map<String, dynamic>? accessTokenParams,
  11. Map<String, String>? accessTokenHeaders,
  12. dynamic httpClient,
  13. BaseWebAuth? webAuthClient,
  14. Map<String, dynamic>? webAuthOpts,
})

Requests an Access Token to the OAuth2 endpoint using the Authorization Code Flow.

Implementation

Future<AccessTokenResponse> getTokenWithAuthCodeFlow(
    {required String clientId,
    List<String>? scopes,
    String? clientSecret,
    bool enablePKCE = true,
    bool enableState = true,
    String? state,
    String? codeVerifier,
    Function? afterAuthorizationCodeCb,
    Map<String, dynamic>? authCodeParams,
    Map<String, dynamic>? accessTokenParams,
    Map<String, String>? accessTokenHeaders,
    httpClient,
    BaseWebAuth? webAuthClient,
    Map<String, dynamic>? webAuthOpts}) async {
  AccessTokenResponse? tknResp;

  String? codeChallenge;

  if (enablePKCE) {
    codeVerifier ??= randomAlphaNumeric(80);

    codeChallenge = OAuth2Utils.generateCodeChallenge(codeVerifier);
  }

  try {
    var authResp = await requestAuthorization(
        webAuthClient: webAuthClient,
        clientId: clientId,
        scopes: scopes,
        codeChallenge: codeChallenge,
        enableState: enableState,
        state: state,
        customParams: authCodeParams,
        webAuthOpts: webAuthOpts);

    if (authResp.isAccessGranted()) {
      if (afterAuthorizationCodeCb != null) {
        afterAuthorizationCodeCb(authResp);
      }

      tknResp = await requestAccessToken(
          httpClient: httpClient,
          //If the authorization request was successfull, the code must be set
          //otherwise an exception is raised in the OAuth2Response constructor
          code: authResp.code!,
          clientId: clientId,
          scopes: scopes,
          clientSecret: clientSecret,
          codeVerifier: codeVerifier,
          customParams: accessTokenParams,
          customHeaders: accessTokenHeaders);
    } else {
      tknResp = AccessTokenResponse.errorResponse();
    }
  } on PlatformException {
    tknResp = AccessTokenResponse.errorResponse();
  }

  return tknResp;
}