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

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 AWS Mobile CLI
npm i -g awsmobile-cli
  1. Configure AWS Mobile CLI
awsmobile configure
  1. Create new AWS Mobile Project
awsmobile init
  1. Add user signin to project
awsmobile user-signin enable
  1. Push updated configuration to the API
awsmobile 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


Languages

Language:JavaScript 66.1%Language:Objective-C 19.6%Language:Python 7.7%Language:Java 6.6%