Combine client_credentials and Custom authentication flow in Cognito? - amazon-web-services

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).

Related

How to validate Aws cognito refreshToken is valid or not in java?

I have to check whether the refresh token which we got from cognito along with access token is valid or not. Means need to check the refresh token is still active or not. Need the code snippets in java.
To see the latest Java V2 (Not V1 - that is no longer recommended to use) and other AWS SDK code examples, look at the brand new Code Catelog that has been released only a month or so. Its is applicable to any supported AWS SDK langangue. This content has hundreds of examples in different programming languages - including Cognito and the AWS SDK for Java v2.
There is a very detailed example for Cognito that works with tokens and authentication.
It performs these steps.
Invokes the signUp method to sign up a user.
Invokes the adminGetUser method to get the user's confirmation status.
Invokes the ResendConfirmationCode method if the user requested another code.
Invokes the confirmSignUp method.
Invokes the initiateAuth to sign in. This results in being prompted to set up TOTP (time-based one-time password). (The response is “ChallengeName”: “MFA_SETUP”).
Invokes the AssociateSoftwareToken method to generate a TOTP MFA private key. This can be used with Google Authenticator.
Invokes the VerifySoftwareToken method to verify the TOTP and register for MFA.
Invokes the AdminInitiateAuth to sign in again. This results in being prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”).
Invokes the AdminRespondToAuthChallenge to get back a token.
See Sign up a user with an Amazon Cognito user pool that requires MFA using an AWS SDK

AWS Cognito - verify token using JWT vs cognito.getUser SDK

I am using the following doc by AWS for verifying the incoming token with Cognito to verify the user in cognito pool:
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
Now I also need to verify one of the custom attributes (email) of that user. (Basically this is to mitigate a case where some user can change their email-id in the API payload to access someone else's details).
The Cognito SDK I found to do this was this : https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html
It works just fine, however this led me to a question :
Since I'm sending access token in this SDK, do I need to use the former jwt-based token verification as well? Because this SDK also handles the case where token is invalid/expired and sends error codes accordingly. Is there something I'm missing which the former case handles and the latter one doesn't ?
Short answer: no, you can ignore the contents of the JWT.
Longer answer: JWT tokens provide a fast way to verify that a user has been authenticated, without the need to check a database or external service. This can be very important in a high-volume application.
However, they have several limitations:
A JWT token is issued with an expiration timestamp. If you rely on the JWT, you do not have a way to forcibly log-out a user until that timestamp expires.
To be secure, your JWT token must be signed using an asymmetric keypair (I mention this simply because a lot of people have implemented their own identity servers incorrectly; Cognito does it right).
The claims that are in the token (and are signed by the identity server) may not be sufficient for your needs. Best practice is to minimize the size of the token, and iirc Cognito follows this practice by only including the user attributes that are directly tied to authentication.
If any of these limitations apply to a particular use-case (and it sounds like the third applies to you), then you'll have to make that external service call to the identity server. And if you do that, and the server reports authentication status, then there's no need to pay attention to the token.

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.

Amazon AWS getAttribute() using AWS.config.credentials

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.

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.