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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
var AWS_REGION = Amazon.RegionEndpoint.USWest2; String POOL_NAME = "xXxXxXxXx"; //Your pool name without the region part AnonymousAWSCredentials cred = new AnonymousAWSCredentials(); using (var provider = new Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient(cred, AWS_REGION)) { //Get the SRP variables A and a var TupleAa = AuthenticationHelper.CreateAaTuple(); //Initiate auth with the generated SRP A var authResponse = provider.InitiateAuth(new InitiateAuthRequest { ClientId = AWS_CLIENT_ID, AuthFlow = Amazon.CognitoIdentityProvider.AuthFlowType.USER_SRP_AUTH, AuthParameters = new Dictionary<string, string>() { { "USERNAME", username }, { "SRP_A", TupleAa.Item1.ToString(16) } } }); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
DateTime timestamp = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now); CultureInfo usCulture = new CultureInfo("en-US"); String timeStr = timestamp.ToString("ddd MMM d HH:mm:ss \"UTC\" yyyy", usCulture); byte[] claim = AuthenticationHelper.authenticateUser(authResponse.ChallengeParameters["USERNAME"], password, POOL_NAME, TupleAa, authResponse.ChallengeParameters["SALT"], authResponse.ChallengeParameters["SRP_B"], authResponse.ChallengeParameters["SECRET_BLOCK"], timeStr ); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
String claimBase64 = System.Convert.ToBase64String(claim); var resp = provider.RespondToAuthChallenge(new RespondToAuthChallengeRequest { ChallengeName = authResponse.ChallengeName, ClientId = "<insert client id here>", ChallengeResponses = new Dictionary<string, string>() { { "PASSWORD_CLAIM_SECRET_BLOCK", authResponse.ChallengeParameters["SECRET_BLOCK"] }, { "PASSWORD_CLAIM_SIGNATURE", claimBase64 }, { "USERNAME", username }, { "TIMESTAMP", timeStr } } }); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
class AuthenticationHelper { // static variables private static String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; public static BigInteger N = new BigInteger(HEX_N, 16); private static BigInteger g = BigInteger.ValueOf(2); public static BigInteger k; public static int EPHEMERAL_KEY_LENGTH = 1024; public static int DERIVED_KEY_SIZE = 16; public static String DERIVED_KEY_INFO = "Caldera Derived Key"; public static SecureRandom SECURE_RANDOM; //static initializer static AuthenticationHelper() { SECURE_RANDOM = SecureRandom.GetInstance("SHA1PRNG"); HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST; byte[] nArr = N.ToByteArray(); byte[] gArr = g.ToByteArray(); byte[] content = new byte[nArr.Length + gArr.Length]; Buffer.BlockCopy(nArr, 0, content, 0, nArr.Length); Buffer.BlockCopy(gArr, 0, content, nArr.Length, gArr.Length); byte[] digest = messageDigest.ComputeHash(content); k = new BigInteger(1, digest); Console.WriteLine(); } [ThreadStatic] private static HashAlgorithm THREAD_MESSAGE_DIGEST = HashAlgorithm.Create("SHA-256"); |
The first function is generating the A and a values. It returns them in a Tuple for convenience.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// return the Tuple of ( A, a ) public static Tuple<BigInteger, BigInteger> CreateAaTuple() { BigInteger a, A; do { a = new BigInteger(EPHEMERAL_KEY_LENGTH, SECURE_RANDOM).Mod(N); A = g.ModPow(a, N); } while (A.Mod(N).Equals(BigInteger.Zero)); return Tuple.Create<BigInteger, BigInteger>(A, a); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public static byte[] authenticateUser(String username, String password, String poolName, Tuple<BigInteger, BigInteger> TupleAa, String saltString, String srp_b, String secretBlock, String formattedTimestamp) { byte[] authSecretBlock = System.Convert.FromBase64String(secretBlock); BigInteger B = new BigInteger(srp_b, 16); if (B.Mod(AuthenticationHelper.N).Equals(BigInteger.Zero)) { throw new Exception("B cannot be zero"); } BigInteger salt = new BigInteger(saltString, 16); // We need to generate the key to hash the response based on our A and what AWS sent back byte[] key = getPasswordAuthenticationKey(username, password, poolName, TupleAa, B, salt); // HMAC our data with key (HKDF(S)) (the shared secret) byte[] hmac; try { HMAC mac = HMAC.Create("HMACSHA256"); mac.Key = key; //bytes bytes bytes.... byte[] poolNameByte = Encoding.UTF8.GetBytes(poolName); byte[] name = Encoding.UTF8.GetBytes(username); //secretBlock here byte[] timeByte = Encoding.UTF8.GetBytes(formattedTimestamp); byte[] content = new byte[poolNameByte.Length + name.Length + authSecretBlock.Length + timeByte.Length]; Buffer.BlockCopy(poolNameByte, 0, content, 0, poolNameByte.Length); Buffer.BlockCopy(name, 0, content, poolNameByte.Length, name.Length); Buffer.BlockCopy(authSecretBlock, 0, content, poolNameByte.Length + name.Length, authSecretBlock.Length); Buffer.BlockCopy(timeByte, 0, content, poolNameByte.Length + name.Length + authSecretBlock.Length, timeByte.Length); hmac = mac.ComputeHash(content); } catch (Exception e) { throw new Exception("Exception in authentication", e); } return hmac; } |
The important part is that the information is hashed with a shared secret S that we compute in the getPasswordAuthenticationKey method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public static byte[] getPasswordAuthenticationKey(String userId, String userPassword, String poolName, Tuple<BigInteger, BigInteger> Aa, BigInteger B, BigInteger salt) { // Authenticate the password // u = H(A, B) HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST; byte[] aArr = Aa.Item1.ToByteArray(); byte[] bArr = B.ToByteArray(); byte[] content = new byte[aArr.Length + bArr.Length]; Buffer.BlockCopy(aArr, 0, content, 0, aArr.Length); Buffer.BlockCopy(bArr, 0, content, aArr.Length, bArr.Length); byte[] digest = messageDigest.ComputeHash(content); BigInteger u = new BigInteger(1, digest); if (u.Equals(BigInteger.Zero)) { throw new Exception("Hash of A and B cannot be zero"); } // x = H(salt | H(poolName | userId | ":" | password)) byte[] poolArr = Encoding.UTF8.GetBytes(poolName); byte[] idArr = Encoding.UTF8.GetBytes(userId); byte[] colonArr = Encoding.UTF8.GetBytes(":"); byte[] passArr = Encoding.UTF8.GetBytes(userPassword); byte[] userIdContent = new byte[poolArr.Length + idArr.Length + colonArr.Length + passArr.Length]; Buffer.BlockCopy(poolArr, 0, userIdContent, 0, poolArr.Length); Buffer.BlockCopy(idArr, 0, userIdContent, poolArr.Length, idArr.Length); Buffer.BlockCopy(colonArr, 0, userIdContent, poolArr.Length + idArr.Length, colonArr.Length); Buffer.BlockCopy(passArr, 0, userIdContent, poolArr.Length + idArr.Length + colonArr.Length, passArr.Length); byte[] userIdHash = messageDigest.ComputeHash(userIdContent); byte[] saltArr = salt.ToByteArray(); byte[] xArr = new byte[saltArr.Length + userIdHash.Length]; Buffer.BlockCopy(saltArr, 0, xArr, 0, saltArr.Length); Buffer.BlockCopy(userIdHash, 0, xArr, saltArr.Length, userIdHash.Length); byte[] xDigest = messageDigest.ComputeHash(xArr); BigInteger x = new BigInteger(1, xDigest); BigInteger S = (B.Subtract(k.Multiply(g.ModPow(x, N))).ModPow(Aa.Item2.Add(u.Multiply(x)), N)).Mod(N); Hkdf hkdf = new Hkdf(); byte[] key = hkdf.DeriveKey(u.ToByteArray(), S.ToByteArray(), Encoding.UTF8.GetBytes(DERIVED_KEY_INFO), DERIVED_KEY_SIZE); return key; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
/* MIT LICENSE Copyright (c) 2017 Markus Lachinger <business@mmlac.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ using Amazon.Runtime; using System; using System.Collections.Generic; using System.Text; using Amazon.CognitoIdentityProvider.Model; using System.Security.Cryptography; using Org.BouncyCastle.Security; using Org.BouncyCastle.Math; using System.Globalization; namespace Com.Mmlac.Blog.IO { class Authentication { private static String AWS_CLIENT_ID = <insert your client ID here as String>; public Authentication() { } public static void LoginUser(String username, String password) { var AWS_REGION = //TODO: change to the region your pool is in! i.e.: Amazon.RegionEndpoint.USWest2 String POOL_NAME = <insert pool name here as String>; // (without the region identifier. It is usually <region>_<name>, just the name part here!) AnonymousAWSCredentials cred = new AnonymousAWSCredentials(); // Identify your Cognito UserPool Provider using (var provider = new Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient(cred, AWS_REGION)) { //Get the SRP variables A and a var TupleAa = AuthenticationHelper.CreateAaTuple(); //Initiate auth with the generated SRP A var authResponse = provider.InitiateAuth(new InitiateAuthRequest { ClientId = AWS_CLIENT_ID, AuthFlow = Amazon.CognitoIdentityProvider.AuthFlowType.USER_SRP_AUTH, AuthParameters = new Dictionary<string, string>() { { "USERNAME", username }, { "SRP_A", TupleAa.Item1.ToString(16) } } }); //Now with the authResponse containing the password challenge for us, we need to //set up a reply //ChallengeParameters SALT, SECRET_BLOCK, SRP_B, USERNAME, USER_ID_FOR_SRP DateTime timestamp = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now); //The timestamp format returned to AWS _needs_ to be in US Culture CultureInfo usCulture = new CultureInfo("en-US"); String timeStr = timestamp.ToString("ddd MMM d HH:mm:ss \"UTC\" yyyy", usCulture); //Do the hard work to generate the claim we return to AWS byte[] claim = AuthenticationHelper.authenticateUser(authResponse.ChallengeParameters["USERNAME"], password, POOL_NAME, TupleAa, authResponse.ChallengeParameters["SALT"], authResponse.ChallengeParameters["SRP_B"], authResponse.ChallengeParameters["SECRET_BLOCK"], timeStr ); String claimBase64 = System.Convert.ToBase64String(claim); //Our response to AWS. If successful it will return an object with Tokens, //if unsuccessful, it will throw an Exception that you should catch and handle. var resp = provider.RespondToAuthChallenge(new RespondToAuthChallengeRequest { ChallengeName = authResponse.ChallengeName, ClientId = AWS_CLIENT_ID, ChallengeResponses = new Dictionary<string, string>() { { "PASSWORD_CLAIM_SECRET_BLOCK", authResponse.ChallengeParameters["SECRET_BLOCK"] }, { "PASSWORD_CLAIM_SIGNATURE", claimBase64 }, { "USERNAME", username }, { "TIMESTAMP", timeStr } } }); Console.WriteLine(""); //Statement for the debugger to hook // From here on you either have your keys and the auth was successful, or you need to prompt your // user for the correct credentials again. Or something else went wrong, the Exception contains the // specific error text returned from AWS } } } /** * Class for SRP client side math. */ class AuthenticationHelper { // static variables private static String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; public static BigInteger N = new BigInteger(HEX_N, 16); private static BigInteger g = BigInteger.ValueOf(2); public static BigInteger k; public static int EPHEMERAL_KEY_LENGTH = 1024; public static int DERIVED_KEY_SIZE = 16; public static String DERIVED_KEY_INFO = "Caldera Derived Key"; public static SecureRandom SECURE_RANDOM; //static initializer static AuthenticationHelper() { SECURE_RANDOM = SecureRandom.GetInstance("SHA1PRNG"); HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST; byte[] nArr = N.ToByteArray(); byte[] gArr = g.ToByteArray(); byte[] content = new byte[nArr.Length + gArr.Length]; Buffer.BlockCopy(nArr, 0, content, 0, nArr.Length); Buffer.BlockCopy(gArr, 0, content, nArr.Length, gArr.Length); byte[] digest = messageDigest.ComputeHash(content); k = new BigInteger(1, digest); Console.WriteLine(); } [ThreadStatic] private static HashAlgorithm THREAD_MESSAGE_DIGEST = HashAlgorithm.Create("SHA-256"); // methods below - all stateless // return the Tuple of ( A, a ) public static Tuple<BigInteger, BigInteger> CreateAaTuple() { BigInteger a, A; do { a = new BigInteger(EPHEMERAL_KEY_LENGTH, SECURE_RANDOM).Mod(N); A = g.ModPow(a, N); } while (A.Mod(N).Equals(BigInteger.Zero)); return Tuple.Create<BigInteger, BigInteger>(A, a); } //raturns the claim public static byte[] authenticateUser(String username, String password, String poolName, Tuple<BigInteger, BigInteger> TupleAa, String saltString, String srp_b, String secretBlock, String formattedTimestamp) { byte[] authSecretBlock = System.Convert.FromBase64String(secretBlock); BigInteger B = new BigInteger(srp_b, 16); if (B.Mod(AuthenticationHelper.N).Equals(BigInteger.Zero)) { throw new Exception("B cannot be zero"); } BigInteger salt = new BigInteger(saltString, 16); // We need to generate the key to hash the response based on our A and what AWS sent back byte[] key = getPasswordAuthenticationKey(username, password, poolName, TupleAa, B, salt); // HMAC our data with key (HKDF(S)) (the shared secret) byte[] hmac; try { HMAC mac = HMAC.Create("HMACSHA256"); mac.Key = key; //bytes bytes bytes.... byte[] poolNameByte = Encoding.UTF8.GetBytes(poolName); byte[] name = Encoding.UTF8.GetBytes(username); //secretBlock here byte[] timeByte = Encoding.UTF8.GetBytes(formattedTimestamp); byte[] content = new byte[poolNameByte.Length + name.Length + authSecretBlock.Length + timeByte.Length]; Buffer.BlockCopy(poolNameByte, 0, content, 0, poolNameByte.Length); Buffer.BlockCopy(name, 0, content, poolNameByte.Length, name.Length); Buffer.BlockCopy(authSecretBlock, 0, content, poolNameByte.Length + name.Length, authSecretBlock.Length); Buffer.BlockCopy(timeByte, 0, content, poolNameByte.Length + name.Length + authSecretBlock.Length, timeByte.Length); hmac = mac.ComputeHash(content); } catch (Exception e) { throw new Exception("Exception in authentication", e); } return hmac; } public static byte[] getPasswordAuthenticationKey(String userId, String userPassword, String poolName, Tuple<BigInteger, BigInteger> Aa, BigInteger B, BigInteger salt) { // Authenticate the password // u = H(A, B) HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST; byte[] aArr = Aa.Item1.ToByteArray(); byte[] bArr = B.ToByteArray(); byte[] content = new byte[aArr.Length + bArr.Length]; Buffer.BlockCopy(aArr, 0, content, 0, aArr.Length); Buffer.BlockCopy(bArr, 0, content, aArr.Length, bArr.Length); byte[] digest = messageDigest.ComputeHash(content); BigInteger u = new BigInteger(1, digest); if (u.Equals(BigInteger.Zero)) { throw new Exception("Hash of A and B cannot be zero"); } // x = H(salt | H(poolName | userId | ":" | password)) byte[] poolArr = Encoding.UTF8.GetBytes(poolName); byte[] idArr = Encoding.UTF8.GetBytes(userId); byte[] colonArr = Encoding.UTF8.GetBytes(":"); byte[] passArr = Encoding.UTF8.GetBytes(userPassword); byte[] userIdContent = new byte[poolArr.Length + idArr.Length + colonArr.Length + passArr.Length]; Buffer.BlockCopy(poolArr, 0, userIdContent, 0, poolArr.Length); Buffer.BlockCopy(idArr, 0, userIdContent, poolArr.Length, idArr.Length); Buffer.BlockCopy(colonArr, 0, userIdContent, poolArr.Length + idArr.Length, colonArr.Length); Buffer.BlockCopy(passArr, 0, userIdContent, poolArr.Length + idArr.Length + colonArr.Length, passArr.Length); byte[] userIdHash = messageDigest.ComputeHash(userIdContent); byte[] saltArr = salt.ToByteArray(); byte[] xArr = new byte[saltArr.Length + userIdHash.Length]; Buffer.BlockCopy(saltArr, 0, xArr, 0, saltArr.Length); Buffer.BlockCopy(userIdHash, 0, xArr, saltArr.Length, userIdHash.Length); byte[] xDigest = messageDigest.ComputeHash(xArr); BigInteger x = new BigInteger(1, xDigest); BigInteger S = (B.Subtract(k.Multiply(g.ModPow(x, N))).ModPow(Aa.Item2.Add(u.Multiply(x)), N)).Mod(N); Hkdf hkdf = new Hkdf(); byte[] key = hkdf.DeriveKey(u.ToByteArray(), S.ToByteArray(), Encoding.UTF8.GetBytes(DERIVED_KEY_INFO), DERIVED_KEY_SIZE); return key; } } } |
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!
Thank you for this code. I tried it and I keep getting the not authorized exception. I was wondering if you knew the solution?
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
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.
Hi
I’m still getting the “not authorized” even we are using the right api key and No secret enabled
Thanks @Markus Lachinger
It worked fine for me
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?
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
Has anyone tried Refreshtoken already? I tried like this
InitiateAuthRequest initiateAuthRequest = new InitiateAuthRequest();
initiateAuthRequest.AuthFlow = AuthFlowType.REFRESH_TOKEN_AUTH;
// User Name is only needed if AuthFlow is REFRESH_TOKEN
//initiateAuthRequest.AuthParameters.Add(“USERNAME”, this.TextBox_Login_userName.Text);
//initiateAuthRequest.AuthParameters.Add(“SECRET_HASH”, null);
initiateAuthRequest.AuthParameters.Add(“REFRESH_TOKEN”, refreshToken);
initiateAuthRequest.AuthParameters.Add(“DEVICE_KEY”, deviceKey);
initiateAuthRequest.AuthParameters.Add(“USERNAME”, userName);
initiateAuthRequest.ClientId = AWS_CLIENT_ID;
var initiateAuthResponseTask = await provider.InitiateAuthAsync(initiateAuthRequest);
But still get invalid refresh token, any ideas?
Many thanks,
Trung.
Thanks you so much for this page, got Cognito working in Unity because of this !
Can’t believe Amazon, can produce this !
Hi!
I’m trying to use this code, but it fails to compile.
What is the BigInteger class? Is from System.Numerics?
And SecureRandom?
Can’t find the reference.
Thanks!
Hi, Thank you for this guide. It’s very helpful. I have been trying to thread my authentication logic because it tends to block the main thread, however all of my threads end when they get to the AuthenticationHelper. I was wondering if you know why this might be. Is there a work around to get the hashing etc. to run on a thread other than the main thread? Thank you, Julien
Hello Markus
Thanks for your good work. I don’t know C# so I’m trying to port this code to Delphi. I’m having trouble understanding two BigInteger constructors:
N = new BigInteger(HEX_N, 16);
k = new BigInteger(1, digest);
I can’t find any C# docs that describe BigInteger constructors taking 2 parameters. Can you point me to their source?
Thanks
David
Hello Markus
Please disregard my inquiry. I found what I need at Bouncy Castle.
Thanks again
David