I made a simple IAM authenticated API that returns a random number. [GET only]
Postman call works ok:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html?shortFooter=true
What is a simple way of getting the postman call to plain javascript
(No npm or webpack)
Thanks heaps
You can use axios and aws4 library in javascript to make api calls and send a signed request respectively.You need to authenticate the user via Cognito and retrieve temporary credentials (access key, secret key, and session token)
let request = {
host: 'myapi.execute-api.us-west-2.amazonaws.com',
method: 'GET',
url: 'https://myapi.execute-api.us-west-2.amazonaws.com/foo/bar',
path: '/foo/bar'
}
let signedRequest = aws4.sign(request,
{
// assumes user has authenticated and we have called
// AWS.config.credentials.get to retrieve keys and
// session tokens
secretAccessKey: AWS.config.credentials.secretAccessKey,
accessKeyId: AWS.config.credentials.accessKeyId,
sessionToken: AWS.config.credentials.sessionToken
})
delete signedRequest.headers['Host']
delete signedRequest.headers['Content-Length']
let response = await axios(signedRequest)
This article might help you with the basic code to get temporary credentials from cognito and authenticate the user.
Related
I want to use kinesis video streams webrtc javascript sdk for producing video stream from a web page.
The sdk readme says i need to supply accessKeyId and secrectAccessKey
signalingClient = new KVSWebRTC.SignalingClient({
channelARN,
channelEndpoint: endpointsByProtocol.WSS,
clientId,
role: KVSWebRTC.Role.VIEWER,
region,
credentials: {
accessKeyId,
secretAccessKey,
},
systemClockOffset: kinesisVideoClient.config.systemClockOffset,
});
Is there a way to make this more secure and avoid supplying the secret access key inside the javascript code?
Doesn't it mean anyone viewing my web page source can take these credentials from the web page and use them to access the signaling channel?
Can I use amplify-js Auth class to use the signaling client with an authenticated user?
Turns out I can use credentials inside the backend, and send a presigned link to the client using the class SigV4RequestSigner.
There's no need to supply credentials on the client side.
Found it in the documentation:
This is a useful class to use in a NodeJS backend to sign requests and send them back to a client so that the client does not need to have AWS credentials.
When creating the SignalingClient you can either specify the credentials or a requestSigner that returns a Promise<string>, see:
https://github.com/awslabs/amazon-kinesis-video-streams-webrtc-sdk-js/blob/master/README.md#class-signalingclient
credentials {object} Must be provided unless a requestSigner is provided.
Be aware that when not using credentials in the browser you will also need to run the KinesisVideoSignalingChannels related code on the server side, because this class does not supports request signer.
For Kinesis, one of the possibilities is to implement in your NodeJS backend a function for signing your URLs.
const endpointsByProtocol = getSignalingChannelEndpointResponse.ResourceEndpointList.reduce((endpoints, endpoint) => {
endpoints[endpoint.Protocol] = endpoint.ResourceEndpoint;
return endpoints;
}, {});
console.log('[VIEWER] Endpoints: ', endpointsByProtocol);
const region = "us-west-2";
const credentials = {
accessKeyId: "XAXAXAXAXAX",
secretAccessKey: "SECRETSECRET"
};
const queryParams = {
'X-Amz-ChannelARN': channelARN,
'X-Amz-ClientId': formValues.clientId
}
const signer = new SigV4RequestSigner(region, credentials);
const url = await signer.getSignedURL(endpointsByProtocol.WSS, queryParams);
console.log(url);
I am not sure how to send signed http request do AppSync GraphQL endpoint. There is no library for do that in AWS.
aws-amplify don't work because works only in browser, not in Lambda function.
aws-sdk for AppSync is only for admin usage, it doesn't have methods for call user side api
It is possible to make IAM signed HTTP request from AWS Lambda? (in some easy way)
i would recommend reading this article: Backend GraphQL: How to trigger an AWS AppSync mutation from AWS Lambda,
quoting the author, https://stackoverflow.com/users/1313441/adrian-hall, we've:
GraphQL is routed over HTTPS. That means we can simulate the GraphQL client libraries with a simple HTTPS POST. Since we are using IAM, we need to sign the request before we deliver it. Here is my code for this:
// ... more code here
// POST the GraphQL mutation to AWS AppSync using a signed connection
const uri = URL.parse(env.GRAPHQL_API);
const httpRequest = new AWS.HttpRequest(uri.href, env.REGION);
httpRequest.headers.host = uri.host;
httpRequest.headers['Content-Type'] = 'application/json';
httpRequest.method = 'POST';
httpRequest.body = JSON.stringify(post_body);
AWS.config.credentials.get(err => {
const signer = new AWS.Signers.V4(httpRequest, "appsync", true);
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());
const options = {
method: httpRequest.method,
body: httpRequest.body,
headers: httpRequest.headers
};
fetch(uri.href, options)
// ... more code here
I've been using it as a template for all my Lambda->AppSync communication!
You can use any graphql client or a sigv4 signed HTTP request. Here's how you create the signature for your request (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). If you attach an execution role to your lambda you can access it access key from lambda environment variables (https://docs.aws.amazon.com/lambda/latest/dg/lambda-environment-variables.html).
This question is already answered but since it came up first for me I thought I'd share another solution.
My use-case was to send a signed request to custom HTTP API hosted on AWS where cognito was used as authentication backend that only had ALLOW_USER_SRP_AUTH enabled (so no ALLOW_ADMIN_USER_PASSWORD_AUTH nor ALLOW_USER_PASSWORD_AUTH)
I ended up combining this example from AWS showing how to do cognito authentication in node:
https://www.npmjs.com/package/amazon-cognito-identity-js (Use case 4)
With the other example from AWS showing how to sign request:
https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-request-signing.html#es-request-signing-node
You plug in the second example into the first example by replacing this line (from first example):
//(...)
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error(error);
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log('Successfully logged!'); // <-- replace this line
}
});
//(...)
Second example needs some tweaks to fit your requirements, things I had to change was:
HTTP method (I needed GET)
signer declaration - I had to change service (replaced es with execute-api)
In signer.addAuthorization I had to use AWS.config.credentials (already initialized by the code from first example) instead of AWS.EnvironmentCredentials('AWS')
Hope this helps someone!
I want to authenticate users using Cognito, with option to use Facebook. User can sign_in/sign_up using either of those options.
I have created Cognito User Pool and Cognito Federated Identity, and also I have created Facebook App for authentication. Both User Pool and Facebook app are connected to Federated identity.
When I sign_up and later authenticate Cognito User via Cognito User Pool, then Cognito returns accessToken, which I store in localStorage on front and use whenever needed for athentication.
I have /authenticate endpoint (express), that takes in username & password, and returns accessToken if all went well. Whenever I make API call that requires auth, I send accessToken that I have in local storage. It goes, more or less as this:
// POST user/authenticate
const authenticationData = {
Username: username,
Password: password
}
authenticationDetails = new AuthenticationDetails(authenticationData)
const userData = {
Username: username,
Pool: userPool()
}
cognitoUser = new CognitoUser(userData)
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (res) => resolve(res), // here I get accessToken
onFailure: (err) => {
console.log('[authenticateUser error]', err)
reject(err)
},
//...
However
When I use Facebook, I do not get accessToken I could use in same fashion. I get accessToken from Facebook via FB.login, I pass it to Cognito to authenticate, and then I don't know what to do, because I cannot get any token that could be used to authenticate API calls, that require Cognito Authentication.
Here's what I do:
await window.FB.login((response) => {
props.userFacebookSignIn(response)
})
// ...
call(foo, 'users/facebook_sign_in', { accessToken: payload.facebookAccessToken })
// ...
// users/facebook_sign_in
AWS.config.region = config.AWSRegion
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'foo',
Logins: {
'graph.facebook.com': facebookAccessToken
}
})
AWS.config.credentials.get((err) => {
// Here I get no errors, I presume that I have logged Facebook user in
const accessKeyId = AWS.config.credentials.accessKeyId
const secretAccessKey = AWS.config.credentials.secretAccessKey
const sessionToken = AWS.config.credentials.sessionToken
// here I can do stuff probably,
// but I would like to receive token that would allow me to do stuff,
// rather than context I can do stuff in
})
While I am doing all of this, I have this feeling, that devs at AWS implemented Cognito as frontend solution, rather than something to be used in backend. Correct me if I am wrong.
Nevertheless, I would like to be able authenticate api calls using Cognito and Facebook interchangeably in express middleware.
Is that possible? Thanks.
I have used federated identity for salesforce single sign on but i imagine the steps will the same. After authenticating with facebook you will recieve and id_token from them in response. You have to pass this as a parameter in the getId method:
var params = {
IdentityPoolId: 'STRING_VALUE', /* required */
AccountId: 'STRING_VALUE',
Logins: {
'<IdentityProviderName>': 'STRING_VALUE',
/* 'graph.facebook.com': ... */
}
};
cognitoidentity.getId(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
In the result you will get an identity id which you can save somewhere so that you don't have to make this call everytime while authenticating. Now take this identity id and make the getCredentialsForIdentity call:
response = client.get_credentials_for_identity(
IdentityId='string',
Logins={
'string': 'string'
},
CustomRoleArn='string'
)
This will finally give you the temporary access key, secret key and session key you need.
I decided to use oAuth.
Here's quick & dirty look on how it's done
In AWS Cognito
1) Set up Cognito User Pool. Add App Client save App client id & App client secret as COGNITO_CLIENT_ID and COGNITO_CLIENT_SECRET
2) Go to Federation > Identity providers and add your Facebook app ID and App secret (both you will find in Facebook app panel)
3) Go to App integration > App client settings click "Select all", set up your Callback URL, mine is localhost:5000/facebook also select Authorization code grant and Allowed OAuth Scopes (save scopes to say: COGNITO_SCOPES)
4) Now go to App integration > Domain name and enter your custom domain; let's say example-app-debug so it's: https://example-app-debug.auth.us-east-1.amazoncognito.com
That's all there is to Cognito
no the Facebook part
5) Settings > Basic add example-app-debug.auth.us-east-1.amazoncognito.com to your App domains - Save Changes
6) In Facebook Login > Settings in Valid OAuth Redirect URIs add this URL: https://example-app-debug.auth.us-east-1.amazoncognito.com/oauth2/idpresponse and Save Changes
and the code
In browser, redirect user to this url when Login w. Facebook button is clicked:
window.location.href =
`https://example-app-debug.auth.us-east-1.amazoncognito.com/oauth2/authorize` +
`?identity_provider=Facebook` +
`&redirect_uri=http://localhost:5000/facebook` +
`&response_type=code` +
`&client_id=${COGNITO_CLIENT_ID}` +
`&scope=${COGNITO_SCOPES}`
this call should come back to you with a code, like this: http://localhost:5000/facebook?code=foo-bar-code Send this code to your backend.
In backend, do this:
const axios = require('axios')
const url = `` +
`https://${COGNITO_CLIENT_ID}:${COGNITO_CLIENT_SECRET}` +
`#example-app-debug.auth.us-east-1.amazoncognito.com/oauth2/token` +
`?grant_type=authorization_code` +
`&code=foo-bar-code` + // <- code that came from Facebook
`&redirect_uri=http://localhost:5000/facebook` +
`&client_id=${COGNITO_CLIENT_ID}`
const response = await axios.post(url)
// response should have access_token, refresh_token and id_token in data
You send access_token, refresh_token and id_token back to frontend and save them in local storage and use them to authenticate and Done.
I am trying to connect to my AWS AppSync API using the plain Apollo Client but I am not sure how to structure the authentication header correctly.
So far I have followed the header authentication documentation here: https://www.apollographql.com/docs/react/recipes/authentication.html
And have this code, which I adapted to include the token call to the Amplify authentication service but it returns a 401 error:
const httpLink = createHttpLink({
uri: '[API end point address]/graphql'
});
const authLink = setContext((_, { headers }) => {
const token = async () => (await Auth.currentSession()).getAccessToken().getJwtToken();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ""
}
}
})
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
})
The only documentation I can find relating to this doesn't provide any technical instructions:
When using Amazon Cognito User Pools, you can create groups that users
belong to. This information is encoded in a JWT token that your
application sends to AWS AppSync in an authorization header when
sending GraphQL operations.
From here: https://docs.aws.amazon.com/appsync/latest/devguide/security.html
I know that token is fine because if I use the AppSync JavaScript API then it works. Is there anywhere I can go to find out how to achieve this or does someone know how?
Edit:
So far i have tried changing this line:
authorization: token ? `Bearer ${token}` : ""
The following attempts:
token
jwtToken: token
authorization: token
Authorization: token
None of these have worked either.
Disclaimer: Never tried it, but here is what I would do:
Check out the AppSync Client code here as a foundation for creating a an Authentication link for Apollo Client and the AppSync server. It looks like that code provides the scaffolding for each of the available authentication methods.
Specifically, if you are trying to use the OPENID_CONNECT method of authentication, it appears as if the JWT token does not need to be prepended by Bearer (line 156).
You can see an example of it on Github from AWS sample.
Works with AppSync but very similar.
// AppSync client instantiation
const client = new AWSAppSyncClient({
url: GRAPHQL_API_ENDPOINT_URL,
region: GRAPHQL_API_REGION,
auth: {
type: AUTH_TYPE,
// Get the currently logged in users credential.
jwtToken: async () => (await Auth.currentSession()).getAccessToken().getJwtToken(),
},
// Amplify uses Amazon IAM to authorize calls to Amazon S3. This provides the relevant IAM credentials.
complexObjectsCredentials: () => Auth.currentCredentials()
});
Link to the AWS repo
I want to use Cognito Federated Entity (allowing signin through Google etc), to allow access to API Gateway for a web javascript application.
I managed to get the Cognito's sessionToken through signing-in with Google but I'm stuck on the API Gateway configuration for enabling the session token.
Is there a good tutorial for this entire Federated Entity authentication workflow?
Thanks!
Since you want to invoke APIs via authenticated Cognito identity, first
Amend the auth role of the identitypool to have api execute policy, you could just attach the managed policy "AmazonAPIGatewayInvokeFullAccess" to the respective role
In API gateway under respective method request, add Authorization as
"AWS_IAM"
You need to sign the request while using "IAM" auth, explained here https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html
Instead of #3, you could generate and download the SDK from the stage panel of your API gateway, and make a call to the api via sdk.
Once you obtain the cognito session, you could make a call using the sdk like below
var apigClient = apigClientFactory.newClient({
accessKey: AWSCognito.config.credentials.accessKeyId,
secretKey: AWSCognito.config.credentials.secretAccessKey,
sessionToken: AWSCognito.config.credentials.sessionToken
});
var params = {
// This is where any modeled request parameters should be added.
// The key is the parameter name, as it is defined in the API in API Gateway.
};
var body = {};
var additionalParams = {
// If there are any unmodeled query parameters or headers that must be
// sent with the request, add them here.
headers: {
'Content-Type': 'application/json'
},
queryParams: {}
};
apigClient.<resource><Method>(params, body, additionalParams)
.then(function(result) {
//
}).catch(function(err) {
//
});