Skip to content

End to end React Native + AWS AppSync GraphQL application with queries, mutations, subscriptions, & user authentication & authorization

Notifications You must be signed in to change notification settings

dabit3/appsync-react-native-with-user-authorization

Repository files navigation

AppSync with User Authorization

A small demo of how to get up and running with AWS AppSync and real world authorization

User Authentication Setup

This step will set up some basic 2 factor user authentication with the current project structure.

If you would like to set up your own user authentation mechanism this would also work, you would just need to update some logic in SignUp.js & SignIn.js.

  1. Install Amplify CLI
npm i -g @aws-amplify/cli
  1. Configure Amplify CLI
amplify configure
  1. Create new AWS Amplify Project
amplify init
  1. Add user signin to project
amplify add auth
  1. Push updated configuration to the API
amplify push

AppSync Configuration

  1. Create new AppSync App

Visit the AppSync console, click "Create API"

  1. Change Authorization Type to "Amazon Cognito User Pool". Choose User Pool created in first series of steps. Set "Default action" as "Allow"

  1. Create the following Schema:
type City {
  id: ID
  name: String!
  country: String
}

type Query {
  fetchCity(id: ID): City
}
  1. Click "Create Resources"

  2. Click "Data Sources" in the left menu, click on the table name under "Resource"

  1. Create an index of "author"

  1. Update "CreateCity" request mapping template to the following:
#set($attribs = $util.dynamodb.toMapValues($ctx.args.input))
#set($attribs.author = $util.dynamodb.toDynamoDB($ctx.identity.username))
{
  "version": "2017-02-28",
  "operation": "PutItem",
  "key": {
    "id": $util.dynamodb.toDynamoDBJson($ctx.args.input.id),
  },
  "attributeValues": $util.toJson($attribs),
  "condition": {
    "expression": "attribute_not_exists(#id)",
    "expressionNames": {
      "#id": "id",
    },
  },
}
  1. Update the "ListCities" request mapping template to the following:
{
  "version": "2017-02-28",
  "operation": "Query",
  "query": {
  	"expression": "author = :author",
    "expressionValues": {
      ":author": { "S": "${ctx.identity.username}" }
    }
  },
  "index": "author-index",
  "limit": $util.defaultIfNull($ctx.args.first, 20),
  "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.after, null)),
}
  1. Run project

About

End to end React Native + AWS AppSync GraphQL application with queries, mutations, subscriptions, & user authentication & authorization

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published