aws-sdk-net-extensions-cognito: Error assigning valid device_key to a CognitoDevice and applying it to CongitoUser.Device prior to calling StartWithSrpAuthAsync (Device Tracking Enabled)

I can’t seem to figure out how to properly add a newly tracked device to a CognitoUser.Device prior to logging in, so the login is tracked for that device key.

Here is the general flow, as an overview:

  • User logs into cognito using StartWithSrpAuthAsync without a device key, as the application is a new device. (SUCCESS)
var userPool = new CognitoUserPool(_settings.UserPoolId, _settings.ClientId, _cognitoClient);
var user = new CognitoUser(userName, _settings.ClientId, userPool, _cognitoClient);
var authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
      Password = password
}).ConfigureAwait(false);

2: The AuthenticationResult object within the response contains a NewDeviceMetadata object, which contains a new DeviceKey (CONFIRMED)

3: The application generates a salt and password verifier and passes it to Cognito, and receives a 200 response.

var confirmDeviceResponse = await ConfirmDeviceAsync(creds, new NewDeviceInfo
{
    GroupKey = authResponse.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,
    Key = authResponse.AuthenticationResult.NewDeviceMetadata.DeviceKey,
    Name = _settings.DeviceName
});

if (confirmDeviceResponse.HttpStatusCode != HttpStatusCode.OK)
{
    throw new Exception(JObject.FromObject(confirmDeviceResponse).ToString());
}

  1. First we save the now-tracked deviceKey to user settings for the application. As a test, we then try immediately refreshing the Cognito session, leveraging InitiateAuthAsync with a DEVICE_KEY AuthParameter and a REFRESH_TOKEN_AUTH AuthFlow:

var userPool = new CognitoUserPool(currentCreds.UserPoolId, currentCreds.ClientId, _cognitoClient);
var user = new CognitoUser(currentCreds.Username, currentCreds.ClientId, userPool, _cognitoClient)
{
     //we have to do this its a bug in the 'StartWithRefreshTokenAuthAsync' 
     //see article https://github.com/aws/aws-sdk-net/issues/844
     SessionTokens = new CognitoUserSession(
         currentCreds.UserPoolIdToken,
         currentCreds.UserPoolAccessToken,
         currentCreds.UserPoolRefreshToken,
         DateTime.Now,
         DateTime.Now.AddHours(1)
     )
};
 user.Device = new CognitoDevice(
     new DeviceType { DeviceKey = currentCreds.DeviceKey }, 
     user
);

var authResponse = await _cognitoClient.InitiateAuthAsync(new InitiateAuthRequest()
{
      AuthFlow = AuthFlowType.REFRESH_TOKEN_AUTH,
      ClientId = currentCreds.ClientId,
      AuthParameters = new Dictionary<string, string>()
      {
          { "USERNAME", currentCreds.Username },
          { "REFRESH_TOKEN", currentCreds.UserPoolRefreshToken },
          { "DEVICE_KEY",  currentCreds.DeviceKey }
       }
});

var newCreds = user.GetCognitoAWSCredentials(
       currentCreds.IdentityPoolId,
       Amazon.RegionEndpoint.USEast1
).GetCredentials();

5: Now, the next time we load the application, we use the device key that now exists:

var userPool = new CognitoUserPool(_settings.UserPoolId, _settings.ClientId, _cognitoClient);
var user = new CognitoUser(userName, _settings.ClientId, userPool, _cognitoClient);


//use existing device key if available
if (_settings.DeviceKey != string.Empty)
{
    var device = new CognitoDevice(new DeviceType
    {
        DeviceKey = _settings.DeviceKey
    }, user);
    user.Device = device;
}
var authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
    Password = password
}).ConfigureAwait(false);


6: Observe error during StartWithSrpAuthAsync() from step 5:

Unhandled Exception: System.ArgumentException: An item with the same key has already been added. Key: DEVICE_KEY
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at Amazon.Extensions.CognitoAuthentication.CognitoUser.StartWithSrpAuthAsync(InitiateSrpAuthRequest srpRequest)

I’ve also tried calling the following after authenticating (for step 5), but receive the same error:

await user.Device.RememberThisDeviceAsync(); 
var authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
    Password = password
}).ConfigureAwait(false);
//use existing device key if available
if (_settings.DeviceKey != string.Empty)
{
    var device = new CognitoDevice(new DeviceType
    {
        DeviceKey = _settings.DeviceKey
    }, user);
    user.Device = device;
    await user.Device.RememberThisDeviceAsync();
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (2 by maintainers)

Most upvoted comments

Word of caution to those stumbling across this (closed) issue - there are threads on SO and another issue here: https://github.com/aws/aws-sdk-net/issues/1054 that all question the implementation and/or documentation related to including device authentication within the user auth flow via the .net SDK.

There are references to a helper called AuthenticationHelper(.cs) but it is not particularly clear where or what this is. It doesn’t appear to be in the SDK or the extensions package and may or may not be required.

I think the fundamental problem with the device authentication with regards to the .net SDK, is a lack of documentation. I am making the assumption of course that it does actually work!

Looks like the code on my is working now! Let me know if you want me to clean it up and create a pull request.