Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
GraphQL Web App with AWS Amplify and IAM Authentication AppSync

AppSync GraphQL Web App with AWS Amplify and IAM…

  • September 24, 2018September 25, 2018
  • by Coder Kai

Howdy! In this tutorial going to create an AppSync GraphQL Web App with AWS Amplify and IAM Authentication using Cognito User Pools. The reason behind this is, if you are creating an web app quickly, the AWS AppSync, Mobile Hub, DynamoDB will come with all the equipments that you need to scale it. So this is such an attempt but um not using the aws amplify cli to create since I would like to know what my configurations looks like when it comes to web. The App will be a react app to quickly show how its done.

AWS Task List

First create AppSync GraphQL API with the data that you want. And change the authentication to IAM

AWS Appsync

After that create the schema using the existing Post example of the Schema. Create the data resources by pressing the Create Resource button in the AppSync. Then the resolvers and everything will be mapped and created.

Create data resources in AppSync

Just for the completeness um adding the partial schema below.

input CreatePostInput {
  title: String!
}

input DeletePostInput {
  id: ID!
}

type Mutation {
  createPost(input: CreatePostInput!): Post
  deletePost(input: DeletePostInput!): Post
}

type Post {
  id: ID!
  title: String!
}

type PostConnection {
  items: [Post]
  nextToken: String
}

type Query {
  getPost(id: ID!): Post
  listPosts(filter: TablePostFilterInput, limit: Int, nextToken: String): PostConnection
}

type Subscription {
  onCreatePost(id: ID, title: String): Post
    @aws_subscribe(mutations: ["createPost"])
  onUpdatePost(id: ID, title: String): Post
    @aws_subscribe(mutations: ["updatePost"])
  onDeletePost(id: ID, title: String): Post
    @aws_subscribe(mutations: ["deletePost"])
}

input TableBooleanFilterInput {
  ne: Boolean
  eq: Boolean
}

input TableFloatFilterInput {
  ne: Float
  eq: Float
  le: Float
  lt: Float
  ge: Float
  gt: Float
  contains: Float
  notContains: Float
  between: [Float]
}

input TableIDFilterInput {
  ne: ID
  eq: ID
  le: ID
  lt: ID
  ge: ID
  gt: ID
  contains: ID
  notContains: ID
  between: [ID]
  beginsWith: ID
}

input TableIntFilterInput {
  ne: Int
  eq: Int
  le: Int
  lt: Int
  ge: Int
  gt: Int
  contains: Int
  notContains: Int
  between: [Int]
}

input TablePostFilterInput {
  id: TableIDFilterInput
  title: TableStringFilterInput
}

input TableStringFilterInput {
  ne: String
  eq: String
  le: String
  lt: String
  ge: String
  gt: String
  contains: String
  notContains: String
  between: [String]
  beginsWith: String
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

Next step is to create the AWS Cognito User Pools and Federated Identities.

Navigate to cognito and create a User Pool by clicking manage user pools. Enter the details that you want for the User Pool and create it. Then make sure you create an App Client in the pool itself afterwards. Untick the Generate App client secret option as well.

After that create the Federated Identity using the client ids. Make sure that you create IAM Roles for the identities. Add the App Client Id and Pool Id to the authentication providers after creating the federated identity

Add authentication providers to the federated identity

Then attach the AWSAppSyncInvokeFullAccess policy to the cognito auth and none auth user roles in AWS IAM.
IMPORTANT: Make sure you create proper policies and permissions for real application and use it. And highly discourage to use None Auth user roles for AppSync in prod.

If you need more detailed version of it, I added a youtube video on this. Check it out.

After that things will be set in the backend for the webapp.

Front End of GraphQL Web App with AWS Amplify and IAM Authentication

I created a sample app in with create-react-app  since it was easier for this tutorial. Then install aws-amplify node module.

yarn add  --save aws-amplify

Then code the AWS Auth and GrapQL endpoints in the index.js file. This doesn’t have to be the place but I just created it for this example only. You can create separate files to configure it which is the case in aws-amplify/cli.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import Amplify from 'aws-amplify';

Amplify.configure({
  Auth: {
    // REQUIRED - Amazon Cognito Identity Pool ID
    userPoolId: 'us-east-1_Orodsda2i',
    // REQUIRED - Amazon Cognito Region
    region: 'us-east-1',
    // OPTIONAL - Amazon Cognito User Pool ID
    identityPoolId: 'us-east-1:kv1348da-7474-4a01-029d-0b50475284895',
    // OPTIONAL - Amazon Cognito Web Client ID
    userPoolWebClientId: 'gvj78fkasbi8aidsf9fuslanvxpa',
  },
  API: {
    'aws_appsync_graphqlEndpoint': 'https://89uvonavoafsdfoahfdsfs.appsync-api.us-east-1.amazonaws.com/graphql',
    'aws_appsync_region': 'us-east-1',
    'aws_appsync_authenticationType': 'AWS_IAM',
  },
});


ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Then create the AWS Query with amplify client as in the following

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Amplify, { API, graphqlOperation } from "aws-amplify";

const ListPosts = `query ListPosts {
  listPosts {
    items {
      id
      title
    }
  }
}`;


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    }
  }

  async componentWillMount() {
    const allPosts = await API.graphql(graphqlOperation(ListPosts));
    console.log(allPosts);
    this.setState({ posts: allPosts.data.listPosts.items });
  }

  render() {
    const { posts } = this.state;
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          {
            posts.map((post, idx) => <div key={idx}>{post.title}</div>)
          }
        </p>
      </div>
    );
  }
}

export default App;

Then you will be able to see how the data is fetched from the GraphQL endpoints using amplify client.

Front End of GraphQL Web App with AWS Amplify and IAM Authentication

Again the important thing is this is only to show how the data is fetched. If you are to properly create it,

  • Create authentication for users with Cognito
  • Allow the GraphQL Endpoints only to the authenticated users using IAM permissions
  • Modify the policies to grant the permissions properly

Well thats about it on  how to create GraphQL Web App with AWS Amplify and IAM Authentication.

The project is uploaded to the github in this link:
https://github.com/sandaruny/appsync-aws-amplify-iam

Checkout this link if you want to know how to do it with react-native apps:

Use AWS GraphQL for React Native Message App

 

 

Query records for a list of keys in GraphQL AppSync AWS using VTL
Why did Facebook pick OCaml?
Coder Kai
A humble developer
aws aws amplify aws app sync aws graphql cognito IAM react.js

Related articles

Copy files from S3 to PostgreSQL RDS
How to copy files from…
How to host GoDaddy domain with AWS EC2
How to host GoDaddy domain…
AWS Ingress ALB with EKS
How to use AWS Ingress…
Frequent errors with Apollo Client
Query definition in GraphQL and…
Query records for a list of keys in GraphQL
Query records for a list…
aws graphql with lambda
How to mutate AWS GraphQL…
Use AWS GraphQL for react native app
Use AWS GraphQL for React…

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • pg soft on Android/iOS React-native heap limit allocation failed error
  • pengeluaran china on Android/iOS React-native heap limit allocation failed error
  • jeannette on How to create Lambda function with Terraform

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress