What is the REST (or CLI) API for logging in to Amazon Cognito user pools - api

How do i make logins happen via Amazon Cognito REST APIs (for user pools) on platforms for which there is no official SDK? - Note that i am asking for user pools - not identity pools.
Synopsis
Amazon cognito provides 3 kinds of logins:
federated logins (creates identity pools) - using social connects like FB, Twitter, G+ etc
AWS managed logins (creates user pools) - using Amazon's own managed signup, signin, forgot password, reset password services
developer provided logins (my custom designed authentication service managed by myself)
I am using the second one (with User Pools)
Amazon cognito has several SDKs for android, iOS, javascript, Xamarin etc. Cognito also provides REST APIs for building on platforms other than those supported by official SDKs. I am building an app for a different platform and, hence, REST API is my only way as there is no official SDK for my platform.
The Cognito REST API provides various endpoints for 'sign up', 'forgot password', 'confirm verification' etc, but surprisingly, the REST API does not have any endpoint for simple signin / login.
From Cognito CLI API docs I have all the OFFICIAL CLI APIs necessary to "signup users", "confirm signups", "change passwords", "verify phone numbers", "forgot passwords" etc. Surprisingly there is no CLI API mentioned for LOGINs. I was hoping there should be some CLI API like "$ aws cognito-idp log-in" just like there is for "$ aws cognito-idp sign-up" or for "$ aws cognito-idp forgot-password" etc.
Also from this getting started tutorial it talks about "*what should be done with tokens received AFTER successful authentication of a user*". However, it doesn't talk about HOW TO make the successful authentication happen on the first place with Cognito User Pool APIs. Examples are available only for Android, iOS, javascript SDKs. There are no authentication examples available for platforms which do not have SDKs.
Hence, How do i make logins happen via Amazon Cognito REST APIs (for user pools) on platforms for which there is no official SDK?

This curl command works for me:
curl -X POST --data #aws-auth-data.json \
-H 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
-H 'Content-Type: application/x-amz-json-1.1' \
https://cognito-idp.us-east-1.amazonaws.com/
Where aws-auth-data.json is:
{
"AuthParameters" : {
"USERNAME" : "yourusername#example.com",
"PASSWORD" : "yourpassword"
},
"AuthFlow" : "USER_PASSWORD_AUTH",
"ClientId" : "75........................"
}
The user pool client must allow USER_PASSWORD_AUTH for this to work - that's an AWS-side setting.

Update:
As you pointed out in the comments below, the authentication flow is documented here: http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html. This might help to clarify the authentication flow
It is somewhat counter-intuitive, but it does make sense for mobile apps where you don't want to have the user explicitly sign in, but instead carry tokens around for the user. Note that there is an explicit signin (login) API in the AWS Userpools SDK for iOS. I have not used it, but I suppose it is just an alternate client side API to get through the same InitiateAuth() followed by a RespondToAuthChallenge() flow. The iOS signin example is documented here - IOS SDK Example: Sign in a User
Original Post:
The Cognito User Pools API documentation for initiating auth is available here
The way it works becomes clearer if you implement a user pools application in one of the SDK's (I did one in Swift for iOS, it is clarified because the logging of the JSON responses is verbose and you can kind of see what is going on if you look through the log).
But assuming I understand your question: In summary you should InitiateAuth() and the response to that (from the Cognito User Pools server) is a challenge. Then you do RespondToAuthChallenge() (also documented in that API doc) and the response to that is an authentication result - assuming that the password / session / token were accepted.
The combination of those two things is, I believe, what you are calling LOGIN, and it works like a login. In the API's, the way it is set up is that attempts to get user information when the user is unauthenticated kicks off that InitiateAuth() and (in iOS anyway) the API does a callback to the code you write to ask for passwords, and send a RespondToAuthChallenge() request etc.

Just to add to #andrewjj's answer. You might get back a challenge (NEW_PASSWORD_REQUIRED) as InitiateAuth response. It is when you are being asked to change passport on initial signin.
You can use Postman or curl command. This example expects Postman being used.
InitiateAuth - This step is same as #andrewjj
Add this to Body as raw values
{
"AuthParameters": {
"USERNAME": "youremail#example.com",
"PASSWORD": "temporary-password",
},
"AuthFlow": "USER_PASSWORD_AUTH",
"ClientId": "2s........................"
}
Set headers
X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth
Content-Type: application/x-amz-json-1.1
Send a request to https://cognito-idp.us-east-1.amazonaws.com/ You might have to change region.
If you receive this response then your are ok, otherwise continue with step 2.
{
"AuthenticationResult": {
"AccessToken": "eyJra........",
"ExpiresIn": 3600,
"IdToken": "eyJra........",
"RefreshToken": "eyJjd........",
"TokenType": "Bearer"
},
"ChallengeParameters": {}
}
RespondToAuthChallenge - this is new step
In case you receive Challenge back like this one:
{
"ChallengeName": "NEW_PASSWORD_REQUIRED",
"ChallengeParameters": {
"USER_ID_FOR_SRP": "1231-......",
"requiredAttributes": "[]",
"userAttributes": "{\"email_verified\":\"true\",\"email\":\"youremail#example.com\"}"
},
"Session": "Sfas......"
}
You need to set new password. Add this to Body as raw values
{
"ChallengeName": "NEW_PASSWORD_REQUIRED",
"ChallengeResponses": {
"USERNAME": "youremail#example.com",
"NEW_PASSWORD": "newpassword"
},
"ClientId": "2s........................",
"Session": "Sfas......(use one from the InitiateAuth response)"
}
Set headers
X-Amz-Target: AWSCognitoIdentityProviderService.RespondToAuthChallenge
Content-Type: application/x-amz-json-1.1
Send a request to https://cognito-idp.us-east-1.amazonaws.com/ You might have to change region.
Do step 1 again to receive tokens.

Sharing curl direct may help to anyone
curl -X POST --data #user-data.json \
-H 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
-H 'Content-Type: application/x-amz-json-1.1' \
https://cognito-idp.<just-replace-region>.amazonaws.com/
file json user-data.json
{"AuthParameters" : {"USERNAME" : "sadfsf", "PASSWORD" : "password"}, "AuthFlow" : "USER_PASSWORD_AUTH", "ClientId" : "csdfhripnv7sq027kktf75"}
make sure your app client does not contain app-secret or create new app without secret. also inside app enable USER_PASSWORD_AUTH

One of the developers from AWS Cognito team here.
To add to #md-abdul-munim's answer, we recommend using one of the client side SDKs. If you are building a REST API and then a front end which talks to those APIs, it is better to just integrate Cognito from your front end.
If you absolutely need to use Cognito from a back end, the authentication APIs will be available with our GA release. In our Cognito User Pools beta release authentication is only available through client SDKs.

From what you have discussed, I consider you are trying to do that from a web frontend. Cause, cognito is providing you the necessary backend support and it expects you to communicate(e.g. authenticate, sign up etc.) from a presentation layer- that's why you found SDK's for different mobile platforms. They also have SDK for web app- the access is available via their Javascript SDK.
Here's a detailed tutorial to achieve what you have asked from a web frontend using their JS SDK-
Accessing Your User Pools using the Amazon Cognito Identity SDK for JavaScript

I have a similar problem and was wondering how to integrate Cognito within an Elixir backend and found this library: https://github.com/aws-beam/aws-elixir
From what I can understand by reading its source code, they ultimately make a POST request that contains the header "X-Amz-Target": "AWSCognitoIdentityProviderService.#{name_of_api_action}" (this is here: https://github.com/aws-beam/aws-elixir/blob/master/lib/aws/cognito_identity_provider.ex#L564). That's without the authorization headers, they are added elsewhere, but I found it interesting. The functions that construct the request URL are following, so you should be able to get an idea of the endpoint that gets called.
I must say I tried following this article written in Japanese - https://qiita.com/yujikawa/items/e79929ed14277102f4b8, and couldn't manage to make it work, maybe because I was not sure what the proper AWS_ENDPOINT environment variable should be. I am currently thinking of trying out the Ruby SDK, from the looks of the documentation it seems fine. But, nonetheless, this information may still help someone.

Thank #andrewjj, your answer is a big help.
Here is additional info for someone who has trouble with client secret. You don't need to turn it off.
You need to generate a secret hash from username, clientId, client secret, as following:
message = bytes(username+app_client_id,'utf-8')
key= bytes(clientSecret,'utf-8')
secret_hash = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
src: https://aws.amazon.com/premiumsupport/knowledge-center/cognito-unable-to-verify-secret-hash/
Then add the secret hash to your AuthParameters, as following:
{
"AuthParameters" : {
"USERNAME" : "...",
"PASSWORD" : "...",
"SECRET_HASH" : "..."
},
"AuthFlow" : "USER_PASSWORD_AUTH",
"ClientId" : "..."
}

Related

Google Photos API - authentication

I'm trying to get list of my shared albums from Google Photos.
I found a enable Photos API in Google Developers Console.
HTTP GET:
https://content-photoslibrary.googleapis.com/v1/sharedAlbums?key=AIzaSyCkXXXXXXXXXXXXXZiOSe9IiyM8E
RESULT:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } } 1
Configuration in developers console:
Please, what I'm doing wrong? Thank you.
Google API need an access token to make sure that the user has the permission to access the feature. Access token is just like cookie that should be send together with the request.
Usually you will need so many setup to get the access token with your own code. But there are a client library that can help you access Google API with small setup.
Access token also has a lifetime, so if you don't use the library you will need to manually refresh the token.
You need to configure OAUth 2.0 credentials (client ID and secret) and not an API key. More details are in the developer documentation here: https://developers.google.com/photos/library/guides/get-started#request-id
The Google Photos library API acts on behalf of a user, that's why you need to authenticate via OAuth 2.0. As part of this request you also need to specify a scope for your users to accept, see this page for more details: https://developers.google.com/photos/library/guides/authentication-authorization
I've been working on a python project to backup google photos library and album info. you can probably modify it to do exactly what you want. It is fully working but does not currently distinguish between shared and private albums.
https://github.com/gilesknap/gphotos-sync
In particular, see https://github.com/gilesknap/gphotos-sync/blob/master/gphotos/authorize.py which handles authentication and authorization for any Google service (it also handles storing the token and refreshing the token).

Format a HTTPS call to Google Cloud using simple API key

I am trying to connect to Google Cloud from an embedded device so I have no access to OAuth authentication. The documents show that I can use simple API key for connecting. I have created a simple API key but I am having problems using it.
I can test the API functions successfully on https://developers.google.com/apis-explorer/?hl=en_US#p/pubsub/v1/ but on this developer's site I don't enter my API key (maybe one is generated automatically in the background).
When I try the same command using curl I get a 401 error:
"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED"
But I am copying the GET or POST command directly from the online API tester and adding my key at the end:
curl -X POST -d '{"policy":{"bindings":[{"role":"roles/editor","members":["serviceAccount:charge...."]}]}}' https://pubsub.googleapis.com/v1/projects/pl..../subscriptions/arriveHomeSub:setIamPolicy?key=AIz....
What am I missing?
With the limited information you have provided, it is tough to identify the root cause but these are some of the possible ones:
You have not used quotes for the URL argument to curl. This could lead to some characters which are part of the URL to be interpreted by your shell in a different manner. Characters like & are usual culprits although they don't seem to be part of the URL you pasted.
curl -X POST -d '{"policy":{"bindings":[{"role":"roles/editor","members":["serviceAccount:charge...."]}]}}' 'https://pubsub.googleapis.com/v1/projects/pl..../subscriptions/arriveHomeSub:setIamPolicy?key=AIz'
You have not described how you're generating your API key and hence I feel that could be one of the possible issues.
You can go over the steps for using Google OAuth 2.0 from Google, it covers a lot about client secrets, access tokens and refresh tokens.
As long as you have your client ID and secret, you can call Google OAuth APIs to generate an access token.
You pass in the current access token as the key argument to your REST API.
Access tokens have very limited lifetime and might need refreshing periodically. If your application needs to periodically refresh access tokens, consider storing the refresh token in your application in a secure manner.

Google Domain API for iOS with access token

I am developing an application with Google Domain API which would manage activities. I have some questions:
1) This application is for iOS , however I do not see any reference to Google frameworks/PODs for GoogleClientBuilder. Is iOS not supported?
2) I was able to go through Google Sign in through "GIDSignInButton" and delegate, and get the access token and refresh token.
However the APIs for writing posts in Google Domain
https://www.googleapis.com/plusDomains/v1/people/userId/activities
does not have "access token" parameter in the header, however it requires Scope Authorization. In 'GIDSignInButton', there is no option of specifying scope.
I have already referred to https://developers.google.com/+/domains/ , the JAVA code mentioned is not at all useful.
I would be grateful, if I can get some direction on this.
You can use two-way to authenticate the user through Google and implement any other Google API services.
1.Using Google API-Objective C client, which is available on GitHub.
Using this method, You can implement the sign in and its has several sample code like Google +, Blogger API integration.
2 Using Google Sign-In for iOS, which is framework based implementation.
In this method, you need to authenticate the user, once the user is authenticated, you can add access token into your each request as a request header.
curl -i -H "Accept: application/json" -H "Authorization: Bearer {{ACCESS_TOKEN}}" "https://www.googleapis.com/plusDomains/v1/people/me/activities/user"
Please make sure that you have right permission, during the sign In the process in order to get any data during the API.

How to obtain a LinkedIn token via Titanium

I want to log in to my application via LinkedIn. This can be done via a call to Cloud.SocialIntegrations.externalAccountLogin() .
However, the function above needs a 'token' parameter. The 'token' is provided by LinkedIn by following the oauth flow(retrieve an authorization code, exchange of the Authorization Code for a Request Token).
Is there an easy way in titanium to obtain this token? I have investigated aaronksaunders's(https://github.com/aaronksaunders/clearlyinnovative.linkedIn) code, and searched on gitt.io. Or do we need to write all of this boilerplate code ourselves?
NOTE: At the moment, I don't want to proxy the call via a server(I prefer not to set up an SSL certificate, etc) and I don't have an appcelerator team or enterprise plan, so I can't use their node(arrow) backend to proxy these calls.
Additional question: is it sufficient to configure the iOS Bundle Identifiers(on the LinkedIn app settings page)? And do I need to use this 'iOS settings' application Id(also on the LinkedIn app settings page)?
I have successfully finished my flow. Everything is explained in this blog post from Ramkumar M: http://shareourideas.com/2012/12/18/linkedin-connect-for-appcelerator-titanium/. The result is achieved by using a modified commonjs module version of the social.js library: https://gist.github.com/rampicos/4320296
This library has a very clean api, the whole flow is nothing more than:
var social = require('social');
var linkedin = social.create({
consumerSecret : CONSUMER_SECRET,
consumerKey : CONSUMER_KEY,
site: 'linkedin'
});
linkedin.authorize(function(){
//callback
});
I don't use the
Cloud.SocialIntegrations.externalAccountLogin()
because the login is done by the social.js library.
LinkedIn app: I have only configured the iOS bundle identifiers.

Error code 403 in Google+ api

I got "error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
When i try to fetch User Profile in Google+ api by https://www.googleapis.com/plus/v1/people/me URL String.If anyone have any suggestion then please tell me as soon as possible.Thanks in advance for your time.
That message implies that you haven't set up a Google APIs console project.
Create a Google APIs Console project
On the Services pane, enable all of the APIs that your project requires.
On the API Access pane, click Create an OAuth 2.0 client ID. A dialog opens. Fill in your project's information. Click Next
Choose the appropriate application type. Based on the tags you used for this post, I am guessing this is an iOS project so select Installed application.
Enter your bundle ID. You don't need to enter an App Store ID until your app is listed there.
Click Create Client ID.
You will see the client ID and client secret values. You will use these values to enable communication with your project and the Google APIs.
If you aren't already using it, see the Google+ iOS SDK and documentation for a full walk through. The task called "write moments" is similar in implementation and demonstrates how to connect to and use the Google+ REST APIs from within an iOS project that uses the SDK.
You'll need to specify the scope of plus.me to get the profile information.
I got the same error and after much hunting I found that, in my case, the Authorization header with the access token was not set. Set Authorization: "Bearer <YOUR_ACCESS_TOKEN>" in the header of the request of EVERY Google API call.
I just want to add a little information here in the rare case that someone runs into this problem.
I have an organization (ORG). I created a second channel (SC) with some playlists, that referenced videos from ORG.
I made the mistake of assuming that because ORG owned SC, that I could use the same oauth credentials from ORG to access both. I was wrong.
I switched credentials and was confused when I could access the playlists but not the videos. Again, I needed credentials for each one separately to access the resources on the respective channel.
Lame, but that was how it was.
BrettJ's answer will cover most of the bases. However, you will also get this error - even when your credentials are properly authenticated - when the scope is not properly set up. I would check the scope setting in your OAuth dance. Make sure your user is permitted to do the thing your code is trying to help them do.
On top of what BrettJ has mentioned, it is important to send the authorization header for the request done to fetch UserProfile in google+ API.
For example, Add the following header
key: Authorization
value: Bearer ya29.Ci-cA_CywoVdVG#######
For what it's worth, I also got this error when using rclone to sync files and my firewall wasn't configured to allow that traffic.