How do I integrate amazon cognito login in postman? - postman

I was using Amazon Cognito user pool for login. When I access my web application, I get a redirect to
https://<domain>.auth.<region>.amazoncognito.com/login?response_type=code&client_id=<client id>&redirect_uri=<callback> .
Once logged in with the username/password of a user from the pool, I will be redirected to the callback URL with the code as a query parameter. I can use this to get tokens. How do I integrate this in postman so that I can use the token for my upcoming request?

I have an example of doing this...
The callback URL as defined in the Cognito User Pool console under App Integration / App client settings.
The URL for the login endpoint of your domain. This will be under Cognito User Pool / App Integration / Domain Name
Client ID is found under Cognito User Pool / General Settings / App clients
List the scopes you want to include in the Access Token. These must be enabled under Cognito User Pool / App Integration / App client settings. These can be either standard or custom scopes. Custom scopes are defined under App Integration / Resource servers and must include the resource server ID (e.g. https://myresource.com/myscope)
Click Request Token
You may now log in to your Cognito User Pool and receive an Access Token!
The problem is that once you have the Access Token it isn't usable within Postman because Cognito expects it to be bare and Postman automatically prepends 'Bearer' to the token:
The token can be used in cURL though:
curl -i -H "Authorization: dyJraWQiOiI1YVcwTUlqN1hBaHg4Yzh4Q3JNT2RsQjhZWjlCR3NQOE9BbkFlVFJtUklRPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI3YmEwZmMzOC01ZDcwkYS05MTI5ZTBmYTUzNTEiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6Imh0dHBzOlwvXC9hcGkubXk5MC5jb21cL3BvbGljZURlcGFydG1lbnRzLnJlYWQiLCJhdXRoX3RpbWUiOjE1NDA1OTIzMTYsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbVwvdXMtZWFzdC0xX2xIbGo4NXpRYSIsImV4cCI6MTU0MDU5NTkxNiwiaWF0IjoxNTQwNTkyMzE2LCJ2ZXJzaW9uIjoyLCJqdGkiOiJhN2JiOWU2MC1kNmY1LTQ3ODYtODMwYi0xODdkZDZmYTZlODAiLCJjbGllbnRfaWQiOiI2MzhlYmZ1dTdiZDRkMXVkYnRzY2pxcnJncyIsInVzZXJuYW1lIjoicm9qbyJ9.O_GAxfFX3IQfLUu5Hxr05Wrk_2QDwNSL8tvDdEU0Dzs9d1XhQPafT6ney6yiGnKPOwsO8HhWdbT1QdDmByjuwQAURf1Da4Au7c-yhfgJcqWuHWZ4mledTSP8ukXqihMb4PoaDdU4JXyOdMLa50dBXVMgJNyXTpIulWOxFhiTW6DeQbnxNDk94cGNz_CTKCEqKStiloFZfLR7ndSrWqdOQ_SU__YV0RyKXZyK5yguv3nkUcI6cuKpbPVIZ5DNdpufbrtOLuZcC6HePBKrbTKjSZCt5-swy3YrwnY4ApTX7QUFzof6FylWaLA_KVP3Zv6ksSJ_IjBMFH1NRVHh4lbsOA" \
https://xxxxx.execute-api.us-east-1.amazonaws.com/v1/myresource/1234

by yl.
Thanks to Robert Jordan for his above postman OAuth2.0 configuration post.
I'll try to cover here the entire Cognito user pool definition part to make it easier.
Ok,
Open the Cognito console and follow the bellow stages:
1) create new user pool
name: Test1
left panel menu->Attributes
Select the following radio buttons:
o Email address or phone number - Users can use an email address or phone number as
their "username" to sign up and sign in.
o Allow email addresses
And checkboxes:
[v] email
[v] name
Screenshot:
Press the [Create Pool] button.
(if not available yet to the wizard - press [Review Details] option on the left panel menu)
2) left panel menu->App Clients
press: [add app client]
App client name: me1
clear all checkboxes but the:
[v] Enable username password based authentication (ALLOW_USER_PASSWORD_AUTH)
Leave Radio buttons as is:
o Enabled (Recommended)
Screenshot:
press [create app client]
3) copy and keep the 'App client id'
this is a string format similar to 5psjts111111117jclis0mu28q
Screenshot:
4) left panel menu->App Client settings
Enabled Identity Providers: [v]Select all
[v] Cognito User Pool
Callback URL(s): put the api gw url or https://www.google.com/
OAuth 2.0
Allowed OAuth Flows
[v] Implicit grant
Allowed OAuth Scopes
[v] openid
Screenshot:
5) left panel menu->Domain name
put a string in the prefix field, for instance: music123456789
check if available using the 'check' button.
your domain now is: https://music123456789.auth.us-east-1.amazoncognito.com
Screenshot:
6) left panel menu->Users and Groups
press [Create user]
Username (Required): Your.Mail#company.com
clear all [v] check boxes
Temporary password: Xx123456!
eMail: Your.Mail#company.com
7) in POSTMAN
Press new Request
enter the 'Authorization' tab
Select TYPE: OAuth 2.0
press the [Get new Access Token] button and fill in:
Token Name: myToken123
Grant Type: select 'implicit' from the listbox
callback URL: https://www.google.com/
(as in clause 4 or in cognito console->App Integration->App client settings)
Auth URL: https://music123456789.auth.us-east-1.amazoncognito.com/login
(as in clause 5 + '/login' suffix, what you have defined in cognito
console->App Integration->Domain Name)
Client ID: 5psjts343gm7gm7jclis0mu28q (the app client id - as in 3,
what you have defined in cognito console->General Settings->App clients)
Scope: openid (as in 4, what you have defined in cognito console->App
client settings->Allowed OAuth Scopes)
COGNITO to OKTA idp configuration
When connecting Cognito to Okta IDP, Configuration should be as follows:
Okta Setup
Cognito Setup
Postman setup

As an addition to very through explanations of Robert Jordan and ylev, I made it work by using the id_token instead of the Access Token.
In the token details page, copy the id_token and add it to the header manually without Bearer prefix:
Source: https://github.com/postmanlabs/postman-app-support/issues/6987

For those wanting to move away from the deprecated "implicit" grant to the recommended "authorization" aka "authorization code" grant, you'll want to have the following in Postman:
Grant Type: Authorization Code (Authorization Code with PKCE would prevent the code from being used by anyone else if it were intercepted in transit but either or... you probably want to start with getting "Authorization Code" working.)
Callback URL: https://oauth.pstmn.io/v1/callback (or whatever Postman sets it to when you check "Authorize using browser"
Auth URL: https://{app name you chose when creating the custom auth domain}.auth.{aws region}.amazoncognito.com/login e.g. https://myapp.auth.us-east-1.amazoncognito.com/login. You can find this in AWS Console -> Cognito -> the user pool -> App Integration tab -> Domain section -> Cognito domain (use the Actions dropdown to create a custom domain if you don't already have one).
Access Token URL: https://{app name}.auth.{aws region}.amazoncognito.com/oauth2/token e.g. https://myapp.auth.us-east-1.amazoncognito.com/oauth2/token.
Client ID: The Client ID corresponding to the "App Client" (e.g. the web app users will be authenticating through Cognito to use), found in AWS Console -> Cognito -> the user pool -> App Integration tab -> App Client List section -> the App Client.
Client Secret: An optional added security measure. This should never be sent to the web app as the client secret could then be extracted by a nefarious user via Chrome Dev Tools or the like. You can (and should) however use Client Secret with backend applications e.g. the API service backing your frontend web app. This is a decision that has to be made in AWS when the App Client is created within the Cognito User Pool, but don't fret- App Clients are easy to create/delete/recreate if you change your mind or pick the wrong setting.
Scope: OAuth uses "scopes" as a means of defining what the application which holds and uses the access token (e.g. some web app) can do/access on behalf of the user whose account it's using. It's similar to authorization in a web app (e.g. only users in the "admin" group can access the settings page) but it's meant to be authorization with respect to a user's metadata, so typically that manifests as user metadata the app has access to, for example the user's calendar or contacts or phone number. OAuth scope is not meant to replace an app's authorization system (e.g. RBAC) so if you're just making some web app and just need Cognito to handle user signup, storing and resetting passwords for users, etc. you can more or less ignore OAuth "scope", though you should probably be setting the "Scope" value in Postman to something like "openid email" (Scopes are separated by a single space and you can't request and obtain the "email" scope without also requesting "openid") so you at least get the user's email address in the access token to compare with your "Users" table in your app's database. Scope makes more sense and becomes more relevant in a scenario where your web app is authenticating with an actual third-party (not your own Cognito user pool), like Facebook or Google. Maybe you're making an app that syncs users' friends' contact data from Facebook to.. I don't know, a CSV file downloaded to your computer for backup purposes. In this case you want to request from Facebook's OAuth server the "friends-list" scope or whatever Facebook decided to call that scope. On the other hand, if you just need Facebook as a means for allowing your users to easily sign in to your app without having to create an account, you don't need the "friends-list" or any other scope from Facbeook (maybe just the scope that gives you the user's email address?).
Other fields:
Client Authentication: Send client credentials in body
Type: OAuth 2.0
Add authorization data to: Request Headers
Sources:
https://www.czetsuyatech.com/2021/01/aws-generate-cognito-access-token.html
https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/
https://api.slack.com/legacy/oauth-scopes

If your client supports USER_PASSWORD_AUTH you can request valid bearer tokens using the aws client.
read -s -p "Password: " && \
aws cognito-idp initiate-auth \
--client-id <client id> \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters "USERNAME=<username>,PASSWORD=$REPLY"
This can be added to Postman under Authorization / Type: Bearer Token.

For Postman 8.5.1 and AWS Chalice + Cognito user pool on the backend I have working example:
Cognito > User pools > > App integration > App client settings
About vars:
{{cognito_callback_url}} - Your Callback URL(s) from App client
settings
{{cognito_auth_url}} - Cognito > User pools >
> App integration > Domain name + /login
(https://.....auth.ap-south-1.amazoncognito.com/login)
{{cognito_client_id}} - Your App client web id from App client
settings
{{cognito_scope}} - Use 'openid'
Now click the Get the new access token in the bottom and authorize yourself using existing user data from pool

I thought i would post some more information about using cognito with an elastic load balancer. AWS load balancers do not current support auth via headers :( you can get it working on postman by copying cookies from a successfull web request into the postman request

The use-case you want to implement can be achieved by using the OAuth 2.0 authorization. If you can get the Auth URL/ Access Token URL, Client ID, and the Client Secret- you should be able to do it.
Here's a link to the documentation of the various authorization types we support including the above mentioned one- https://www.getpostman.com/docs/v6/postman/sending_api_requests/authorization.
Cheers.

Related

Google api credentials screen stuck spinning after adding a postman redirect URI

I have created a new project in Google cloud console to experiment with Google OAuth flows. I have therefore set up OAuth web app client credentials using
APIs & Services -> Credentials -> Create Credentials -> OAuth Client ID -> Web Application
I want to be able to experiment with postman to request authorisation codes, access/refresh tokens etc. Once in the Create OAuth client ID I therefore add a postman callback URI (https://oauth.pstmn.io/v1/callback) to the credentials' Authorised Redirect URIs as described here. However when I click CREATE at the bottom of the Create OAuth client ID screen, the screen does not update and just keeps spinning. I have waited for over 20 mins but to no avail. Is this a callback URI validation problem such that Google won't allow me to add this redirect URI to the credentials? I have tried to add the domain oauth.pstmn.io to the authorised domains in the project settings but to no avail. When I don't include the redirect URI, the credentials are created with no problem and I am returned to the main APIs & Services -> Credentials screen.
The user that I am using to make these changes owns the project and therefore I do not suspect it is a Google user permissions issue. I have also added the minimum number of fields (project name and support email) to the OAuth consent screen settings. I have also tried this whole process logged in on a different machine.
It seems that at least one api scope needs to be added to OAuth consent screen->Scopes before you set a redirect URI. This video explains the entire setup.
https://documenter.getpostman.com/view/8296678/TzXtGzS2
you can use this public collection to learn more about how to set up auth token for google APIs

How to add a user to user pool in cognito with google sign in without using hosted UI

I am trying to authenticate and add a user to the user pool using google sign in by following the video tutorial given here . This does almost exactly what I want to achieve with my application , i.e, provide a login page with an option to authenticate through google (using hosted UI), the user then gets added to the user pool in cognito if not already present and gets redirected along with access token in the redirected url. I wanted to add the sign in with google button on the already existing login page I have currently and authenticate user from there.
Is there a way through which I can receive access and ID tokens for an end user without using Hosted UI ? Can someone explain(or point me out to documentation) explaining flow along with the APIs hit from the moment a user clicks on the sign in with google button that redirects to a google sign in page to the point cognito returns access and ID tokens for the user ?
Behind the scene the Hosted UI is a set of HTTPS endpoints that you can call yourself with specific parameters. What you are interested in is the AUTHORIZATION endpoint (https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html).
There you must submit the identity_provider parameter (in your case the one for Google) and the callback that is https://HOSTED_UI_DOMAIN/oauth2/idpresponse.
This will hit the Hosted UI with a specific client ID (so that it can create a new user in User Pool). In your client configuration you need to specify the callback URL being your application. This endpoint will then receive an authorization code from Cognito that can be exchanged for a set of JWT by calling another endpoint in Hosted UI: https://HOSTED_UI_DOMAIN/oauth2/token.

AWS: Cognito integration with a beta HTTP API in API Gateway?

Amazon Web Services introduced a beta release of HTTP API as a new product on API Gateway early last month. Its authentication is managed using JSON Web Tokens and configured with a form asking for
"Name of the Authorizer"
"Identity Source... a selection expression that defines the source of the token"
"Issuer URL"
I'm not very familiar with authentication protocols at all or what these form fields are asking, and currently the documentation from AWS on how to configure this to work with Cognito is sparse. I'm not totally comfortable configuring this without guidance due to my lack of experience. Another Stack Overflow user seemed to have a similar issue but didn't get an answer.
AWS is using JWT Bearer Grant for this purpose.
Draft Specification here.
It allows HTTP API Gateway to accept JWT Tokens in the incoming Authorization HTTP header containing a self-contained JWT access token issued by third-party authorization servers (like Cognito, Azure AD, etc).
API Gateway validates the incoming JWT Token by matching the 'iss' value with the issuer URL to see if it can trust this token.
Try with these values.
Name of the authorizer: Registered client name in your Cognito User Pool .
Identity Source: Leave it as default, $request.header.Authorization .
Issuer URL: Check the metadata URL of your Cognito User Pool (construct the URL in this format :: https://cognito-idp.[region].amazonaws.com/[userPoolId]/.well-known/openid-configuration :: look for a claim named "issuer". Copy its Value and paste it here.
Audience: Client ID of your Registered client in Cognito
Good Luck!
cheers,
ram
Used #ram answer to get through, and was able to implement this
1.Name of the authorizer:
AWS Cognito > User pools > App Integration > App client settings > App client :
Example : xxxxxx_app_clientWeb
2.Identity Source : $request.header.Authorization
3.Issuer URL
construct the URL to get Cognito user pool metadata ( https://cognito-idp..amazonaws.com//.well-known/openid-configuration)
Example :
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141/.well-known/openid-configuration
open the URL and you will see a json
take the "issuer" value
Example :
"issuer":"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141"
Take: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141
4. Audience: AWS Cognito > User pools > App Integration > App client settings > App clientID
Example :
ID 9sptej55gii5dfp08ulplc343
Take: 9sptej55gii5dfp08ulplc343
This video explains the whole process and configuration like no other.
https://www.coursera.org/lecture/building-modern-java-applications-on-aws/use-amazon-cognito-to-sign-in-and-call-api-gateway-s226R
I am thankful that the video is public.
Note: (As far as I know) The course is from AWS but offered to the public through different MOOC websites (not just this one).
Once you have read & played enough, you will start seeing the gems within the details.
Token for example, is mentioned in many docs, but it can be Access / Id / Refresh Token. If you don't realize about this you can be wasting your time.
For example the "Implicit grant" doesn't provide a Refresh-Token, so you cannot renew your Access-Token and trying to do it is useless.

How to get the accesstoken from alexa after account linking with azure AD

I tried to connect my Alexa AWS Lambda function (node.js 6.10) with Azure Activ Directory to my Azure-Cloud-API. After reading the documentation from amazon and many tutorials I have now a working Account Linking. That means, I can link the Account of the Skill inside the Alexa-App on my smartphone.
AccountLinking for my Custom Skill:
{Data from my azure portal}
Authorization Grant Type: Auth Code Grant
Authorization URI: {OAUTH 2.0 AUTHORIZATION ENDPOINT}
Access Token URI: {OAUTH 2.0 TOKEN ENDPOINT}
Client ID: b9c6[...]bc60 {Application ID}
Client Secret: {Client Secret}
Client Authentication Scheme: Credentials in request body
scope: openid
domain: empty
redirect urls: --> In Azure portal as ALLOWED TOKEN AUDIENCES and Reply URLs defined
In my aws lambda function I get the event request from alexa like the documentation says with properties for version, session, context, request...
My understanding of the documentation is, that the token I need for the Azure-Cloud-API-Request should be here: session.user.accessToken
But this token doesn't look like the one I need and after my test runs I get always "Unauthorized" back.
The Token looks something like this and is 1252 characters long:
AQABAAAAAADX8GCi6Js6SK82TsD2Pb7rqGN56iHT_YSxlSr1RAdXucGs0S3ykOaw0XZ1WnjJotqZAn9BH7agRbP0VQv2rnJuRw_aJil7 [...] JIEO2Ap4wuG-tTwiSmZBfbLhyYtwQmxLAkqiLApqFmBYcyu-dnzlVV4liDGyTQ7gAXufd3zt7QGmi3UfP1aL9f5NBeXbmxnU6FHRzF10QZa19pTQgNTtIK8oIAA
If I configure postman and send a request to the azure activ directory I get a accessToken like this (1168 characters long):
eyJ0eXAiOiJKV1QiLCJhbGc [...] Ezbk5aY2VEYyJ9.eyJhdWQiOiJodHRwczovL21ldGVvcmEtYXBwLmF [...] kY5MWVUUXdBQSIsInZlciI6IjEuMCJ9.KJco47-FdJ_eeqv38LL [...] YK_4JqCRDw
This one looks like a jwt-token and if I copy this token directly in my aws lambda function and use this one for the Azure-Cloud-API-Request it works (until the token expires).
Now I'm not sure if there is a problem in my configuration of the account linking? Or do I have to do something with the token from alexa to get the real one? Or is the real token somewhere else and I have to fetch it there?
Thanks a lot for your help!
Amazon Documentation "Alexa Skills Kit":
https://developer.amazon.com/docs/custom-skills/link-an-alexa-user-with-a-user-in-your-system.html
EDIT (Solution) 11.06.2018
Authorization Grant Type: Auth Code Grant
Authorization URI: {OAUTH 2.0 AUTHORIZATION ENDPOINT} + ?resource= + {Application ID}
Access Token URI: {OAUTH 2.0 TOKEN ENDPOINT}
Client ID: b9c6[...]bc60 {Application ID}
Client Secret: {Client Secret} App>Settings>Keys new Key with expiration date = 2 years
Client Authentication Scheme: Credentials in request body
scope: empty
domain: empty
redirect urls: --> In Azure portal as ALLOWED TOKEN AUDIENCES and Reply URLs defined
It sounds like you haven't completed the account linking sequence for your skill. After setting the account linking configuration you need to open the Alexa app (on your phone or https://alexa.amazon.com) and go to your new skill and link your account. Once that is successful you will get a token in request.Session.User.AccessToken.
The blog post: https://blogs.msdn.microsoft.com/premier_developer/2017/12/09/amazon-alexa-skills-authenticated-by-azure-active-directory-and-backed-by-asp-net-core-2-0-web-api-hosted-on-azure/ needs to be updated with the following:
You can ignore the sections about the "front end" app registration.
In Alexa account linking section update URLs to use login.microsoftonline.com instead of login.windows.net
ClientId to be the Application Id of the "back end" app registration
The ?resource= has to be set and has to be the same as the audience parameter for the JWT bearer options. This is ClientId if you use the .Net Core 2.0 template in Visual Studio.
The client secret (key) that is used can not be one that "Never Expires". Use a 1 or 2 year duration.
In addition to Nate's answer and following the addition of ?resource= to the Authorisation URI, I had to give the API permission Azure Active Directory Graph > User.Read on the App Registration and Grant Admin Consent to it.
Without this permission, the account linking would throw an error. If you have similar issues, try your OAuth values with Postman and check the Postman Console for error messages

Empty page for the sign-up and sign-in pages hosted by AWS Cognito

I have created the user pool and added new users to the user pool. My requirement is to use the default sign up/login page provided by cognito. So after retrieving the domain name for the hosted page it renders an empty page.
By simply entering the domain ends in several errors in the console. Appreciate if any one has identified the root cause for this.
If you simply add a /login to your existing URL you'll start to get useful error messages:
https://praedictio.auth.eu-west-1.amazoncognito.com/login
It's not documented very well, but your URL also requires some parameters:
client_id - relates to the app for the identity provider.
redirect_url - should match your redirect url from the UserPool app settings.
response_type - token (or code).
https://praedictio.auth.eu-west-1.amazoncognito.com/login?response_type=code&client_id=(client_id)&redirect_uri=(encoded uri)
URL should be in the following format:
https://domain/login?response_type=code&client_id=client_id&redirect_uri=your_callback_url
Variables can be found in AWS > Amazon Cognito > User Pool > App Integration Tab
Domain:
Client ID of the App
Callback URL of the App
Pleaser refer Cognito document for more info.