Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a new user using AWS Cognito Ruby SDK?

I would like to know how to register a new user using AWS Cognito Ruby SDK.

So far I have tried:

Input

AWS_KEY = "MY_AWS_KEY"
AWS_SECRET = "MY_AWS_SECRET"

client = Aws::CognitoIdentityProvider::Client.new(
  access_key_id: AWS_KEY,
  secret_access_key: AWS_SECRET,
  region: 'us-east-1',
)

resp = client.sign_up({
  client_id: "4d2c7274mc1bk4e9fr******", # required
  username: "[email protected]", # required
  password: "Password23sing", # required
  user_attributes: [
    {
      name: "app", # required
      value: "my app name",
    },
  ],
  validation_data: [
    {
      name: "username", # required
      value: "true",
    },
  ]
})

Output

Aws::CognitoIdentityProvider::Errors::NotAuthorizedException (Unable to verify secret hash for client 4d2c7274mc1bk4e9fr*****)

References

https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/CognitoIdentityProvider/Client.html#sign_up-instance_method

like image 431
ipegasus Avatar asked Oct 18 '25 14:10

ipegasus


1 Answers

If your app client is configured with a client secret, most of the client requests require you to include a 'secret hash' in the options parameters of the request. The Cognito docs describe the secret hash thusly:

The SecretHash value is a Base 64-encoded keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message. The following pseudocode shows how this value is calculated.

Base64 ( HMAC_SHA256 ( "Client Secret Key", "Username" + "Client Id" ) )

The docs also make it clear via a glob of sample Java that you are expected to roll your own. After a bit of experimenting I was able to successfully complete a sign_up call with the following (my test pool was set up to require email and name attributes):

def secret_hash(client_secret, username, client_id)
  Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', CLIENT_SECRET, username + CLIENT_ID))
end

client = Aws::CognitoIdentityProvider::Client.new(
  access_key_id: AWS_KEY,
  secret_access_key: AWS_SECRET,
  region: REGION)

username = '[email protected]'
resp = client.sign_up({
         client_id: CLIENT_ID,
         username: username,
         password: 'Password23sing!',
         secret_hash: secret_hash(CLIENT_SECRET, username, CLIENT_ID),
         user_attributes: [{ name: 'email', value: username },
                           { name: 'name', value: 'Bob' }],
         validation_data: [{ name: 'username', value: 'true' },
                           { name: 'email', value: 'true' }]
       })

CLIENT_SECRET is the app client secret that can be found under General Settings > App Clients.

Result:

#<struct Aws::CognitoIdentityProvider::Types::SignUpResponse
 user_confirmed=false,
 code_delivery_details=nil,
 user_sub="c87c2ac8-1480-4d15-a28d-6998d9260e73">
like image 177
rmlockerd Avatar answered Oct 20 '25 04:10

rmlockerd