How to set twitter app consumer credentials in amazon cognito via CLI - bash

Trying out this from the CLI
aws cognito-identity update-identity-pool \
--identity-pool-id MyIdentityPoolId \
--identity-pool-name MyIdentityPoolName \
--allow-unauthenticated-identities \
--supported-login-providers graph.facebook.com=MyFacebookAppId,api.twitter.com=MyTwitterConsumerKey;MyTwitterConsumerSecret \
--region $MyRegion
The CLI response says:
{
"SupportedLoginProviders": {
"api.twitter.com": "MyTwitterConsumerKey",
"graph.facebook.com": "MyFacebookAppId"
},
"AllowUnauthenticatedIdentities": true,
"IdentityPoolName": "MyIdentityPoolName",
"IdentityPoolId": "MyIdentityPoolId"
}
MyTwitterConsumerSecret: command not found
Unlike configuring facebook (which requires only one credential (the FacebookAppId), configuring twitter requires 2 credentials (ConsumerKey and ConsumerSecret).
If i am delimiting the 2 credentials by a semi-colon, looks like only the first part is getting set in the twitter configuration for amazon cognito. Screenshot attached.
What is the format to pass BOTH ConsumerKey and ConsumerSecret for configuring twitter?
I referred to these AWS docs:
Update Identity Pool via CLI
Create Identity Pool via CLI
Configuring Twitter/Digits with Amazon Cognito

Ok. How silly. Simply needed to scope the credentials for --supported-login-providers within double-quotes.
--supported-login-providers graph.facebook.com="MyFacebookAppId",api.twitter.com="MyTwitterConsumerKey;MyTwitterConsumerSecret"
Then it worked.
{
"SupportedLoginProviders": {
"api.twitter.com": "MyTwitterConsumerKey;MyTwitterConsumerSecret",
"graph.facebook.com": "MyFacebookAppId"
},
"AllowUnauthenticatedIdentities": true,
"IdentityPoolName": "MyIdentityPoolName",
"IdentityPoolId": "MyIdentityPoolId"
}
Screenshot attached.

Related

Debugging lambda locally using cdk not sam

AWS CDK provides great features for developers. Using CDK deveolper can manage not only total infrastructure but also security, codepipeline, ...
However I recently struggling something. I used to debug lambda using SAM for local debugging. I know how to set up CDK environment, and debug CDK application itself. But I can't figure out how to debug lambda application inside CDK.
Can anyone help me?
As of 4/29/2021, there's an additional option for debugging CDK apps via SAM. It's in preview but this blog post covers it : https://aws.amazon.com/blogs/compute/better-together-aws-sam-and-aws-cdk/.
Basically, install the AWS CLI and AWS CDK. The install the SAM CLI - beta, available here : https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk-getting-started.html.
Then you can run command's like:
sam-beta-cdk build sam-beta-cdk local invoke sam-beta-cdk local invoke start-api and even emulate the Lambda service with sam-beta-cdk local start-lambda
You can use SAM and CDK together as described here. In particular:
Run your AWS CDK app and create a AWS CloudFormation template
cdk synth --no-staging > template.yaml
Find the logical ID for your
Lambda function in template.yaml. It will look like
MyFunction12345678, where 12345678 represents an 8-character unique
ID that the AWS CDK generates for all resources. The line right
after it should look like: Type: AWS::Lambda::Function
Run the function by executing:
sam local invoke MyFunction12345678 --no-event
if you are using VSCode, you can set up a launch action to run the current file in node to test it locally. All you need to do is hit F5 on the file you want to test.
You will need to add the following at the end of your handler files so that when executed in node the handler gets executed:
if (process.env.NODE_ENV === "development" && process.argv.includes(__filename)) {
// Exercise the Lambda handler with a mock API Gateway event object.
handler(({
pathParameters: {
param1: "test",
param2: "code",
},
} as unknown) as APIGatewayProxyEvent)
.then((response) => {
console.log(JSON.stringify(response, null, 2));
return response;
})
.catch((err: any) => console.error(err));
}
Add this to your launch configurations in your .vscode/launch.json:
"configurations": [
{
"name": "Current TS File",
"type": "node",
"request": "launch",
"args": ["${relativeFile}", "-p", "${workspaceFolder}/tsconfig.json"],
"runtimeArgs": ["-r", "ts-node/register", "-r", "tsconfig-paths/register", "--nolazy"],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"envFile": "${workspaceFolder}/.env",
"smartStep": true,
"skipFiles": ["<node_internals>/**", "node_modules/**"]
},
The ts-node and tsconfig-paths are only needed if using Typescript. You must add those with npm i -D ts-node tsconfig-paths if you dont already have them.
Before you run any of the sam local commands with a AWS CDK application, you must run cdk synth.
When running sam local invoke you need the function construct identifier that you want to invoke, and the path to your synthesized AWS CloudFormation template. If your application uses nested stacks, to resolve naming conflicts, you also need the stack name where the function is defined.
# Invoke the function FUNCTION_IDENTIFIER declared in the stack STACK_NAME
sam local invoke [OPTIONS] [STACK_NAME/FUNCTION_IDENTIFIER]
# Start all APIs declared in the AWS CDK application
sam local start-api -t ./cdk.out/CdkSamExampleStack.template.json [OPTIONS]
# Start a local endpoint that emulates AWS Lambda
sam local start-lambda -t ./cdk.out/CdkSamExampleStack.template.json [OPTIONS]

AWS CDK Cross Account Lambda Deployment Permission Issue

I followed the following tutorial to create a Lambda deploy pipeline using CDK. When I try to keep everything in the same account it works well.
https://docs.aws.amazon.com/cdk/latest/guide/codepipeline_example.html
But my scenario is slightly different from the example because it involves two AWS accounts instead one. I maintain application source code and pipeline
in the OPS account and this pipeline will deploy the Lambda application to the UAT account.
OPS Account (12345678) - CodeCommit repo & CodePipeline
UAT Account (87654321) - Lambda application
As per the aws following aws documentation (Cross-account actions section) I made the following changes to source code.
https://docs.aws.amazon.com/cdk/api/latest/docs/aws-codepipeline-actions-readme.html
Lambda stack expose deploy action role as follows
export class LambdaStack extends cdk.Stack {
public readonly deployActionRole: iam.Role;
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
...
this.deployActionRole = new iam.Role(this, 'ActionRole', {
assumedBy: new iam.AccountPrincipal('12345678'), //pipeline account
// the role has to have a physical name set
roleName: 'DeployActionRole',
});
}
}
In the pipeline stack,
new codePipeline.Pipeline(this, 'MicroServicePipeline', {
pipelineName: 'MicroServicePipeline',
stages: [
{
stageName: 'Deploy',
actions: [
new codePipelineAction.CloudFormationCreateUpdateStackAction({
role: props.deployActionRole,
....
})
]
}
]
});
Following is how I initiate stacks
const app = new cdk.App();
const opsEnv: cdk.Environment = {account: '12345678', region: 'ap-southeast-2'};
const uatEnv: cdk.Environment = {account: '87654321', region: 'ap-southeast-2'};
const lambdaStack = new LambdaStack(app, 'LambdaStack', {env: uatEnv});
const lambdaCode = lambdaStack.lambdaCode;
const deployActionRole = lambdaStack.deployActionRole;
new MicroServicePipelineStack(app, 'MicroServicePipelineStack', {
env: opsEnv,
stackName: 'MicroServicePipelineStack',
lambdaCode,
deployActionRole
});
app.synth();
AWS credentials profiles looks liks
[profile uatadmin]
role_arn=arn:aws:iam::87654321:role/PigletUatAdminRole
source_profile=opsadmin
region=ap-southeast-2
when I run cdk diff or deploy I get an error saying,
➜ infra git:(master) ✗ cdk diff MicroServicePipelineStack --profile uatadmin
Including dependency stacks: LambdaStack
Stack LambdaStack
Need to perform AWS calls for account 87654321, but no credentials have been configured.
What have I done wrong here? Is it my CDK code or is it the way I have configured my AWS profile?
Thanks,
Kasun
The problem is with your AWS CLI configuration. You cannot use the CDK CLI natively to deploy resources in two separate accounts with one CLI command. There is a recent blog post on how to tell CDK which credentials to use, depending on the stack environment parameter:
https://aws.amazon.com/blogs/devops/cdk-credential-plugin/
The way we use it is to deploy stacks into separate accounts with multiple CLI commands specifying the required profile. All parameters that need to be exchanged (such as the location of your lambdaCode) is passed via e.g. environment variables.
Just try to use using the environment variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
Or
~/.aws/credentials
[default]
aws_access_key_id=****
aws_secret_access_key=****
~/.aws/config
[default]
region=us-west-2
output=json
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
It works for me.
I'm using cdk version 1.57.0
The issue is in the fact that you have resources that exist in multiple accounts and hence there are different credentials required to create those resources. However, CDK does not understand natively how to get credentials for those different accounts or when to swap between the different credentials. One way to fix this is to use cdk-assume-role-credential-plugin, which will allow you to use a single CDK deploy command to deploy to many different accounts.
I wrote a detailed tutorial here: https://johntipper.org/aws-cdk-cross-account-deployments-with-cdk-pipelines-and-cdk-assume-role-credential-plugin/

Aws Ruby SDK credentials from file

I would like to store my credentials in ~/.aws/credentials and not in environmental variables, but I am struggling.
To load the credentials I use (from here)
credentials = Aws::SharedCredentials.new({region: 'myregion', profile_name: 'myprofile'})
My ~/.aws/credentials is
[myprofile]
AWS_ACCESS_KEY = XXXXXXXXXXXXXXXXXXX
AWS_SECRET_KEY = YYYYYYYYYYYYYYYYYYYYYYYYYYY
My ~/.aws/config is
[myprofile]
output = json
region = myregion
I then define a resource with
aws = Aws::EC2::Resource.new(region: 'eu....', credentials: credentials)
but if I try for example
aws.instances.first
I get the error Error: #<Aws::Errors::MissingCredentialsError: unable to sign request without credentials set>
Everything works if I hard code the keys
According to the source code aws loads credentials automatically only from ENV.
You can create credentials with custom attributes.
credentials = Aws::Credentials.new(AWS_ACCESS_KEY, AWS_SECRET_KEY)
aws = Aws::EC2::Resource.new(region: 'eu-central-1', credentials: credentials)
In your specific case, it seems there is no way to pass custom credentials to SharedCredentials.
If you just do
credentials = Aws::SharedCredentials.new()
it loads the default profile. You should be able to load myprofile by passing in :profile_name as an option.
I don't know if you can also override the region though. You might want to try to loose that option, see how it works.

How to use passport-local to authenticate in composer rest server

I want to use passport-local to authenticate user to login into composer rest server like other passport strategies ( e.g passport-github,passport-google).
So first I try to set COMPOSER_PROVIDER variable like this
"local": {
"provider": "local",
"module": "passport-local",
"usernameField": "username",
"passwordField": "password",
"authPath": "/auth/local",
"successRedirect": "/",
"failureRedirect": "/"}
Then i run the server in docker (with mongo as persisted datasource) and add some user in database collection
The question is what's next step that i need to use this passport.Because i run this command and still get response with 401 Unauthorized
curl -H "Content-Type: application/json" -X POST -d
'{"username":"{USER_NAME}","password":"{USER_PASSWORD}"}'
http://localhost:3000/auth/local
Is it not enough to use this passport? Does i need to start another service to locally authenticate this login (e.g. GitHub oAuth Application )?
It is possible to customize your composer-rest-server, based on the loopback framework, according to your requirements.
I suggest to read this tutorial from the official documentation.
https://hyperledger.github.io/composer/latest/integrating/customizing-the-rest-server
I wanted to do that also initially, but then I just edit the server.js file on the composer rest server for basic auth at the end.
check where your composer-rest-server is stored
npm root -g
Open where server.js is located
cd /home/ubuntu/.nvm/versions/node/v8.10.0/lib/node_modules/composer-rest-server/server
Add this to the code
const basicauth = require('basicauth-middleware');
app.use(basicauth('username', 'password!');

How to hide password in shell script duing ARM template deployment

I am using ARM template to deploy Azure VM.
template.json
"adminPassword": {
"type": "securestring"
}
parameters.json
"adminPassword": {
"value": null
}
When I use "null" in parameters, It will ask me enter password during deployment.
When I enter the adminPassword during deployment, it is showing as plaintext, But I want it to hidden (such as ******)
How can I achieve this?
As 4c74356b41 said, currently, there is no way to do it directly.
You could use Azure Key Vault to avoid the password showing as plain text.
Key Vault can store two types of information: Keys (Certificates) and Secrets. In your scenario, you need use Secrets. You need create a secrets in KeyVault.
##get password don't show plaintext
read -s password
azure keyvault create --vault-name 'ContosoKeyVault' --resource-group 'ContosoResourceGroup' --location 'East Asia'
azure keyvault secret set --vault-name 'ContosoKeyVault' --secret-name 'SQLPassword' --value "$password"
After this you'll need to enable the Key Vault for template deployment.You can do this using the following commands:
azure keyvault set-policy --vault-name Contoso --enabled-for-template-deployment true
You need modify your parameter like below:
"adminPassword": {
"reference": {
"keyVault": {
"id": "/subscriptions/<subscription-guid>/resourceGroups/<group name>/providers/Microsoft.KeyVault/vaults/<vault name>"
},
"secretName": "<seccret name>"
}
},
You could refer this template: 101-vm-secure-password.

Resources