How to pass AWS credentials from react

120 views Asked by At

I am using AWS SDK aws-sdk/client-batch in my react to start an AWS batch job. For this I want to pass my AWS credentials so that my batch job can start.

I know there are few different ways of passing the credentials to AWS, but if I were to use react what is the best way to pass the credentials?

Currently my code is:

import React, { useState, useEffect } from 'react';
import { BatchClient, SubmitJobCommand, CancelJobCommand, DescribeJobsCommand } from "@aws- 
sdk/client-batch"

const App = () => {
 const [ batchClient, setBatchClient ] = useState(null);
 const [ submittedJobDetails, setSubmittedJobDetails ] = useState(null);
 const [ jobDetails, setJobDetails ] = useState(null);
 const [ error, setError ] = useState(null);
 const [ cancelSuccess, setCancelSuccess ] = useState(null);

 useEffect (() => {
    const awsConfig = {
         region: "us-east-1",
    };
const client = new BatchClient(awsConfig);
setBatchClient(client);
}, []);

const startBatchJob = async () => {
try{
   const params = {
             jobDefinition: "my-login-test",
             jobName: "my-poc",
             jobQueue: "my-jq-alpha",
         };
         if (!batchClient) {
             setError('Batch client not initialized..')
             return;
         }
         const command = new SubmitJobCommand(params);
         const data = await batchClient.send(command);
         console.log('Batch job started successfully: ', data);
         setSubmittedJobDetails(data.jobId);
         setError(null);
     } catch (error) {
         console.error('Error starting batch job: ', error);
         setError('Error starting Batch job');
         setSubmittedJobDetails(null);
     }
 };

return (
     <div>
       <h1>AWS Batch Job Submission</h1>
       <button onClick={startBatchJob}>Start Batch Job</button>
       <button onClick={cancelBatchJob}>Cancel Batch Job</button>
       {submittedJobDetails && (
         <div>
             <h2>Submitted Job Details: </h2>
             <pre>{JSON.stringify(submittedJobDetails, null, 2)}</pre>
         </div>
       )}
     </div>
  );
}
export default App;

Not an expert of react so I am not exactly sure where to set the AWS credentials here?

Any help is much appreaciated.

1

There are 1 answers

0
Angel Pizarro On

You want to authenticate a user that can assume a AWS IAM role to take actions on your AWS resources.

The AWS JavaScript SDK documentation has an example for using Cognito user pool to list the objects in a private S3 bucket from a HTTP client (in this case a browser).

The AWS SDK Javascript samples GitHub repo also has an example for using SQS which may provide you some hints for your own code.