authenticateWithUsernamePasswordNoContext method

Future<CarpUser> authenticateWithUsernamePasswordNoContext({
  1. required String username,
  2. required String password,
})

Authenticate to this CARP service using a username and password.

Use only if you know what you are doing! This method is used only if neither authenticate nor authenticateWithUsernamePassword works for you, i.e. you do not have access to a BuildContext.

This method uses a POST request to the Identity Server to get an access token. The discovery URL is used to find the Identity Server.

Return the signed in user (with an OAuthToken access token), if successful. Throws a CarpServiceException if not successful.

Implementation

Future<CarpUser> authenticateWithUsernamePasswordNoContext({
  required String username,
  required String password,
}) async {
  final url = app.authURL.replace(pathSegments: [
    ...app.authURL.pathSegments,
    'protocol',
    'openid-connect',
    'token',
  ]);
  final body = {
    'client_id': app.clientId,
    'client_secret': app.clientSecret ?? '',
    'username': username,
    'password': password,
    'grant_type': 'password',
  };
  final headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  final response = await http.post(url, body: body, headers: headers);

  // Json to map the response
  final jsonResponse = json.decode(response.body);
  final tokenResponse =
      convertToTokenResponse(jsonResponse as Map<String, dynamic>);
  CarpUser user = getCurrentUserProfile(tokenResponse);
  user.authenticated(OAuthToken.fromTokenResponse(tokenResponse));

  currentUser = user;

  return user;
}