Amazon AWS getAttribute() using AWS.config.credentials - amazon-web-services

I have just started with Amazon Cognito and I want to use it for my web application. I want to develop a stateless app, in which I SignUp/SignIn using Cognito and then using the JWT token in rest of the requests.
I have implemented sign-up and sign-in flow in Node.js using amazon-cognito-identity-js package and then using the JWT token to call a lambda function using aws-sdk. Things are as expected till here.
But now the issue is with different user operations like get attribute, verify attribute, update password etc. as listed #
https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html
All of these operations require cognitoUser object and in the documentation they are using userPool.getCurrentUser(); expression.
And I have read somewhere that this method returns the last authenticated user. So I think this expression userPool.getCurrentUser(); will cause conflicts. For example if UserB logs in after UserA and UserA tries to update his password, it will not work.
Can someone suggests me what are the possible solutions?
Should I store the cognitoUser object in session at server side ?
[This solution breaks my stateless requirement and I will have to maintain session on server side.]
Is there any way to perform these operations using JWT token ?
Please suggest if you can think of any other better approach to implement Cognito in web app.
Thanks.

We have a stateless app using cognito and lambdas.
The way we have set it up is to not call lambdas directly but to use Api Gateway and lambda-proxy integration.
If you call lambdas directly from your front end code and are using the cognito tokens for authentication then you need to put a lot of logic in each lambda to validate the token, e.g. download the relevant keys, check the signature of the jwt, timestamps, issuer etc. If you use API gateway then you can just create a cognito authorizer and place it in front of your lambdas.
We pass the id_token when making api calls, then the call is validated by the authorizer and the lambda receives all the current attributes set up in the user pool. This means we don't need to make additional calls to get attributes.
For changing the user passwords this can be done from the front-end of the app by calling the cognito api with the access_token if you have allowed it in the user pool client setup.

Related

Validating jwt token in REST api

I have a doubt regarding the jwt token validation done by the REST api and was not able to find a simple yes/no answer. Assume that everything is being transferred over HTTPS.
I have the following setup
React app
REST API
AWS Cognito that handles the user registration/login
When a user wants to login, then the React app would call the AWS Cognito api and validate the credentials. If valid, Cognito will send back a jwt token (that will contain the necessary meta data) that can be passed to the REST API. Now I see two options
the backend verifies that the jwt token was not altered using the rfc spec. If valid, the api extracts the necessary meta data and continues to process the request
The backend verifies the validity of the jwt token, but also calls the Cognito service to verify the metadata in the token.
I think that since everything is handled over HTTPS and the fact that its hard create a valid token then the first point is enough. There is no need to have an extra call over the wire. Am I wrong ?
Found the following question from softwareengineering.stackexchange.com which pretty much answers my question. Link
The local validation of the JWT token is enough when the token was created with asymmetric encryption.

Serverless AWS - is it worth using custom authorizers (as a lambda)?

Hey I am getting started with the serverless framework, apigateway, lambdas and authorizers.
Here my questions:
In order to verify a proper JWT token (which seems nowadays the best solution for serverless authentication), I would need a client id. Since the authorizer lambda is not capable(?) of reaching any other parameters of the request into the lambda except for the token itself, this is a difficult task to do. How can I achieve this?
Since with every authenticated call, an additional lambda is called, my costs are doubled?! May be I am misunderstanding something here, but it seems to me like implementing a method for verifying my token without using the authorizer is cheaper and I don't need to implement the authorizer lambda itself.
The whole point of OAuth2 is that at the point of authorization you don't care who the bearer presenting you with a token is or which client they are using (web app, Postman, etc.), only that the token is valid for whatever the token bearer is trying to do. You trust that the authentication has happened because the token issuer has done the authentication.
When you talk about the aud(audience) (from comments) in JWTs, which may or may not be included dependent on the JWT issuer, this is intended to reflect the service or services that the JWT is valid for.
This could for example have a value of 'myAPIName' or 'myAPIName/test' or even ['myAPIName/test1', 'myAPIName/test2'].
If you need to validate an individual aud claim you have two choices, you can either have different Lambdas authorizing different api routes and methods with hardcoded aud variables or you can get the name of the api being called and map it back to something that would match an aud claim.
For example the method arn for the incoming request can be found in event.methodArn. This looks like arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/ potentially with [{resource}/[{child-resources}]] dependent on your implementation. With a bit of string manipulation, you could map this back to the format of an audience claim (whatever that looks like for you).
If you would rather work an api name instead of an api name you can use the apigateway.getrestapi method for whatever sdk you are using. Documentation on this method for the JavaScript sdk can be found here.
The JWT may have a sub(subject claim), again dependent on implementation of the JWT issuer, this could relate to any of your users (or at least the users the JWT issuer knows about). Validating this beyond checking the signature of the JWT is pointless. The best you could do is check if that user exists and only if you have access to the same user database that the JWT issuer does. Although this can be used to ensure that UserA only has access to UserA's data. Again, you are trusting that the fact a bearer has a token is proof that they have authenticated (proved who they are).
I hope that answers part one of your question.
In regards to part 2, the advantage of using a Lambda Authorizer over doing the authorization in the target Lambda is caching.
So envisage I have a token valid for one hour and I call your API once every second for 30 minutes (1,800 calls). You have a Lambda authorizer with a response cache time of 10 minutes. That means you check the JWT 3 times for 1800 api calls.
But if you do the validation of that token in your target Lambda, you are doing that processing 1,800 times.
There is authentication with AWS Cognito which will allow you to use authentication outside your application and still being able to let your application divide the users into subgroups based on custom roles or similar.
If for some reason you cannot use AWS Cognito (Why not?) there is both the possibility of custom authentication (the same for each function with SLS) or even authenticating with custom code inside each lambda function.
I would recommend to use Cognito, and only custom if you know you need it.

Combine client_credentials and Custom authentication flow in Cognito?

Wondering if it's possible to combine using the client credentials OAuth flow in Cognito with a custom authentication flow as described here: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html
I know about custom authentication flows in Cognito, but I am not so well versed in OAuth itself. But as far as I understand it, the client credentials flow, is unrelated to a user? Because in that case, I would think it is impossible to use a custom authentication flow since the SDK documentation states the following (taken from the AWS node.js SDK):
The authentication parameters. These are inputs corresponding to the AuthFlow that you are invoking. The required values depend on the value of AuthFlow:
[...] For CUSTOM_AUTH: USERNAME (required)
If the value passed as USERNAME in the CUSTOM_AUTH flow is not a known user in Cognito, the lambda trigger for the custom flow will never be executed. And since it is never executed, it is not possible to use the USERNAME parameter to pass any other data to the lambda trigger (you can of course use custom authentication parameters, but you also need a valid USERNAME).

Cognito user pool for single admin

I'm trying to create a personal blog using s3 and lambda. I already have the API setup but I'm trying to figure out how to make the blog post requests more secure by requiring an authorization token in order to access the API Gateway.
I believe this can be done with cognito user pools but is usually used with many users not a single admin user. However, if there's another way I should go about this then I'm all ears.
You can implement this by:
Creating a User Pool in Cognito
If you are using the Hosted UI login pages, I recommend having the pages send a code response rather than a token response because you can call the token endpoint to get all the appropriate tokens.
Call your token endpoint with the code you receive in Step 2 (it'll be in the URL when you are redirected back to your site) to retrieve the ID, Access, and Refresh Tokens.
Once you have your cognitoUser tokens, you can wrap your blog publish function with a token check function to ensure that your token is up-to-date and send the updated token to your publish blog callback.
Send the user token in your headers: { Authorization: token } API Call.
In API Gateway, choose the Method Request in your Blog Post API and select your Cognito User Pool name under authorizers.
As long as the token you send is valid, the Method Request is all you need to update in order to secure the ability to post.

Can I use AWS User Pools as a directory service from a Spring app?

Is it possible to use AWS Cognito User Pools as an authentication and authorisation provider for a Spring Boot app running in EC2?
The user pools seem to provide a lot of the regsiter/login/email/forgotpassword etc plumbing, that I can make use of in an AngularJS front end.
If the front end does all the auth (in javascript), can a java (spring) backend verify tokens passed to it from the front end, and if so how?
Or, can/should the calls to Cognito come from the backend, and again, if so how? Do I need to use the AWS Android mobile SDK?
(I've looked at Lambdas and Api Gateways but they are not what I am after at the moment).
Either one of those options should work, depending a bit on your app requirements. The former does have the benefit of sending user credentials over the wire less often than the latter.
If you want to verify the tokens with your first suggestion, you could do one of a few things. Cognito vends an id token, a refresh token, and an access token upon a user authenticating. Any call that takes an access token (i.e. GetUser) does validation on that access token. Alternatively, you could make a call to refresh the tokens, which will do validation on the refresh token. More information on the tokens Cognito vends is available here. Token refreshing is done through the Cognito auth flow, using challenge name REFRESH_TOKEN or REFRESH_TOKEN_AUTH.
If you opt to go with the second one, AWS does have multiple SDKs for various languages, including Java. These all support the Cognito APIs, but Cognito does use SRP to sign users in. The client side calculations are fairly complex, so you might not want to take that on yourself. You could rip our calculations from the SDK on Github, or you could use the admin no SRP flow described here.