makePreAuthenticatedURL method

Future<Uri> makePreAuthenticatedURL({
  1. required String webApplicationClientID,
  2. required String webApplicationURI,
  3. String? state,
})

Implementation

Future<Uri> makePreAuthenticatedURL({
  required String webApplicationClientID,
  required String webApplicationURI,
  String? state,
}) async {
  if (!preAuthenticatedURLEnabled) {
    throw AuthgearException(Exception(
        "makePreAuthenticatedURL requires preAuthenticatedURLEnabled to be true"));
  }
  if (!(sessionState == SessionState.authenticated)) {
    throw AuthgearException(
        Exception("makePreAuthenticatedURL requires authenticated user"));
  }
  var idToken = await _sharedStorage.getIDToken(name);
  if (idToken == null || idToken.isEmpty) {
    throw const PreAuthenticatedURLIDTokenNotFoundError();
  }
  final deviceSecret = await _sharedStorage.getDeviceSecret(name);
  if (deviceSecret == null || deviceSecret.isEmpty) {
    throw const PreAuthenticatedURLDeviceSecretNotFoundError();
  }
  final tokenRequest = OIDCTokenRequest(
    grantType: GrantType.tokenExchange,
    clientID: webApplicationClientID,
    requestedTokenType: RequestedTokenType.preAuthenticatedURLToken,
    audience: await _apiClient.getApiOrigin(),
    subjectTokenType: SubjectTokenType.idToken,
    subjectToken: idToken,
    actorTokenType: ActorTokenType.deviceSecret,
    actorToken: deviceSecret,
  );
  final tokenExchangeResult = await _apiClient.sendTokenRequest(tokenRequest);

  // Here access_token is pre-authenticated-url-token
  final preAuthenticatedURLToken = tokenExchangeResult.accessToken;
  final newDeviceSecret = tokenExchangeResult.deviceSecret;
  final newIDToken = tokenExchangeResult.idToken;
  if (preAuthenticatedURLToken == null) {
    throw AuthgearException(
      Exception("unexpected: access_token is not returned"),
    );
  }

  if (newDeviceSecret != null) {
    await _sharedStorage.setDeviceSecret(name, newDeviceSecret);
  }

  if (newIDToken != null) {
    _idToken = newIDToken;
    idToken = newIDToken;
    await _sharedStorage.setIDToken(name, newIDToken);
  }

  return await internalBuildAuthorizationURL(
    OIDCAuthenticationRequest(
      responseType: ResponseType.preAuthenticatedURLToken,
      responseMode: ResponseMode.cookie,
      redirectURI: webApplicationURI,
      clientID: webApplicationClientID,
      xPreAuthenticatedURLToken: preAuthenticatedURLToken,
      idTokenHint: idToken,
      prompt: [PromptOption.none],
      state: state,
    ),
  );
}