AWS Cognito SRP Login in C# / .NET 6

1 Flares Twitter 0 Facebook 0 Google+ 0 Reddit 1 LinkedIn 0 StumbleUpon 0 Filament.io 1 Flares ×
Visual Studio variables table screenshot showing successful authentication

Successful Authentication with AWS Cognito using C#

In my latest project I decided to use AWS Cognito User Authentication instead of rolling my own or using something like Cloudfoundry’s UAA. My application is written in C# and is using the AWS SDK for .NET. AWS Cognito supports two ways to authenticate a user, either via SRP or sending the plain credentials to AWS. The problem with the latter approach is however that it needs IAM credentials and therefore should not be used in an end user application. Unfortunately only the iOS, Android and JavaScript SDKs support login via SRP. In this blog post I am going to show how SRP authentication can be achieved with the .NET SDK in C#.

The problem I ran into when trying to use an off-the-shelf SRP library like the one from Bouncy Castle is that Cognito builds a custom M1 message to verify the claim and that there is no documentation for it. In order to make SRP work on C# I looked at the Android SDK codebase and ported it to C#.

A full code example with proper using statements is included at the end of the post.

Update: AWS released a Developer Preview of their CognitoAuthentication Extension Library that should address this issue. Keep reading if you care about the details of how SRP works or how to get it working manually on platforms that the official SDK still doesn’t support ;)

 

 

Initiating the Auth

The first step to starting the authentication flow is to generate the A value and send an InitiateAuthRequest. The AuthenticationHelper class is doing the heavy lifting for SRP and will be discussed further below.

This code snippet shows how to set up the CognitoIdentityProvider by using anonymous AWS credentials, as we don’t want to ship IAM credentials to users, providing the region the pool is located in and finally sending the request with the A value and the username to authenticate.

After making this request, Cognito will return a response containing a dictionary with the information necessary to generate the validation claim: SALT, SECRET_BLOCK, SRP_B, USERNAME, USER_ID_FOR_SRP.

These fields are passed to the authenticateUser method of the AuthenticationHelper class to generate the claim. In addition to these fields, Cognito requires a timestamp, formatted in a specific way. It is important that it is formatted in the US culture to be accepted.

Note: The Android code does not honor the sent USER_ID_FOR_SRP field therefore the code here also only uses the initially submitted username. This might need to be adapted when logging in with an alias or email address.

The resulting claim now needs to be encoded via Base64 and sent back to Cognito. If the claim can be verified, it will return the user’s tokens. If there was an error, the request will throw an exception containing the reason for failure.

At this point the tokens can be stored in case of a successful authentication and be used in other requests.

 

SRP Algorithm and Hash

The above was the easy part and what was already present in the C# AWS Cognito SDK. The following is showing the SRP math ported from the AWS Cognito Android SDK. In order to ease debugging, I made the class stateless, which means in contrast to the Android SDK this class will return the A and a values and expect them back as input variables later.

First part of the AuthenticationHelper class in the initialization with a static N and defining a thread-local HashAlgorithm.

The first function is generating the A and a values. It returns them in a Tuple for convenience.

The authenticateUser method is taking every necessary parameter as a separate parameter instead of i.e. handling the unpacking of the InitiateAuthResponse object directly. Again, this was done for ease of debugging and can easily be modified to be more suitable to other use cases.

The authenticateUser method is generating the claim message, or M1, for Cognito to verify. It contains pool name, username, secret block and other information.

The important part is that the information is hashed with a shared secret S that we compute in the getPasswordAuthenticationKey method.

Please note the use of a Hkdf class that is used to derive the key. This code is compatible with an implementations like the one found in this gist by CodesInChaos. Unfortunately it does not contain any licensing information and therefore should only be used as instructional material to implement your own class, in addition to Wikipedia. Of course any other HKDF implementation can be used as well, just make sure you don’t mix up the parameter order!

 

Congratulations, these are all the pieces necessary to authenticate with AWS Cognito using C#!

 

 

Full Code Sample

Following is the code in one file ready to compile. Please read about the Hkdf class in the paragraph above if you haven’t yet! Another caveat is that this implementation is not checking for every issue that can arise, it is not catching every single exception that can occur. This would bloat the example and is left as an exercise to the reader. Most times a catch-all block around the full authentication call is sufficient as one can hardly recover from an exception inside this code. One noteworthy exception — no pun intended ;) — is differentiating whether the authentication threw an unexpected error or the credentials were invalid!

Copy & pasting the code it will throw compilation errors where custom information needs to be added, like client ID, region and pool ID.

You can click the <> symbol in the code snipped below to get an unformatted version to copy.

 

 

Debug Notes

  • There are still issues using a client secret with the SDK: StackOverflow thread
  • Java uses unsigned byte arrays, so in order to compare the byte arrays, call this for byte[] bite:
    sbyte[] signed = Array.ConvertAll(bite, b => unchecked((sbyte)b));  (via SO)
  • A good starting point for the Android SDK code is in CognitoUser.java:1783

 

I hope this article helped you with authenticating against AWS Cognito using SRP in C#.

What do you think? Do you have any comments, improvements, questions or just enjoyed the read? Go write a comment below and I try to respond as quickly as possible :)

Help others discover this article as well: Share it with your connections!

 

Subscribe to the blog to get informed immediately when the next post is published!

1 Flares Twitter 0 Facebook 0 Google+ 0 Reddit 1 LinkedIn 0 StumbleUpon 0 Filament.io 1 Flares ×

6 thoughts on “AWS Cognito SRP Login in C# / .NET

  1. Reply Shilpi Kanade Mar 28,2017 4:33 PM

    Thank you for this code. I tried it and I keep getting the not authorized exception. I was wondering if you knew the solution?

  2. Reply gokhanacer Apr 7,2017 6:27 AM

    Hi,

    I copied your code. But I’m alway getting this error:
    Amazon.CognitoIdentityProvider.Model.NotAuthorizedException
    Incorrect username or password.

    Could you help me please?

    Sincerely

  3. Reply Markus Lachinger May 10,2017 11:49 PM

    These “not authorized” exceptions are extremely hard to debug, make absolutely sure you have the right apikey and that those have NO secret enabled.

    It works for me and a few others, so we know the code is working if set up properly. If you double checked your inputs, the next debugging step is unfortunately going to i.e. the Java code, running it with a debugger, and stepping through the individual methods. Once the Java code has generated an A value and gotten a challenge from Congito, you can plug these into the C# code and call them directly with the predefined data (that’s why the code is broken up the way it is) and try to verify that the same output is generated.

  4. Reply Minh Dinh May 24,2017 9:51 AM

    Thanks @Markus Lachinger
    It worked fine for me

  5. Reply VNick May 29,2017 5:14 AM

    Hi Markus, thank you for your example.
    I am trying to use that code in a xamarin app but I receive a “not authorized” error which reports: “Unable to verify secret hash for client “.
    Isn’t necessary to provide also the secret_client_id?

  6. Reply VNick May 29,2017 6:06 AM

    Sorry for misunderstanding, I have now clear the reason of my error thanks to the the first “Debug notes”, there is no utility to publish my comment.
    Thanks again

Leave a Reply