amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

Unable to make unauthenticated/anonymous requests to graphql api even though cli gives the option to

Open rayhaanq opened this issue 8 years ago • 27 comments

This is a similar issue to https://github.com/aws-amplify/amplify-js/issues/1252 During auth installation via the cli, the cli gives the option to allow unauthenticated login. However. when trying to make requests to my graphql api (also setup via the clie) without any @auth directive, it's still not possible to make requests. I still get the same No current user error. I've checked the identity pool settings and it looks like the unauth and auth roles are both set. I assume something isn't set up correctly? Am I missing some permissions/policies on my unauth role?

Expected behaviour It seems like a standard use case to have some methods to be public and some requiring authorisation. For example, all reads for a Post type are publicly accessible, however all writes require an authenticated user that's the owner of the Post. And comments require any authenticated user to write one for a Post, but any public/anonymous user can read the comments.

rayhaanq avatar Oct 01 '18 12:10 rayhaanq

It sounds as if you are trying to use IAM auth but the API is setup to use AWS Cognito User Pools. Is this correct? The CLI does not currently support GraphQL APIs with IAM but support for this is on the backlog and will be worked on as soon as resources are available.

After creating the API, you can go to the AppSync console's settings page and enable IAM auth instead of user pools auth to verify if this fixes your issue.

mikeparisstuff avatar Oct 01 '18 21:10 mikeparisstuff

Thanks @mikeparisstuff for getting back to me. I did try to use IAM auth and queries from the console worked fine. But when I try to make requests to my api from my frontend, I get the same No current user error when no user is logged in, but when a user is logged in I get a 403 error (Incomplete signature exception) with the message:

Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=my-auth-token"

rayhaanq avatar Oct 02 '18 11:10 rayhaanq

@rayhaanq you need to update the authentication type in your UI as well. Like this:

import amplifyConfig from './src/aws-exports';
amplifyConfig.aws_appsync_authenticationType = 'AWS_IAM';
Amplify.configure(amplifyConfig);

@mikeparisstuff once IAM auth is set up, how do you actually configure permissions for the use case mentioned above? I have this:

type Thing 
  @model 
  @auth(
    rules: [
      {allow: owner, identityField: "cognitoIdentityId"},
    ]
  )
{
  id: ID!
  name: String!
}

It'd be nice to be able to write a rule that looks something like this:

{allow: unauthenticated, queries: [get, list]}

Thoughts?

xvvvyz avatar Oct 03 '18 01:10 xvvvyz

@cadejscroggins I tried the snippet above. Now I get a 401 with a Permission denied error. This is whether the user is logged in or logged out.

rayhaanq avatar Oct 03 '18 16:10 rayhaanq

@rayhaanq ah, you need to give your auth/unauth IAM roles appropriate permissions. The AWSAppSyncInvokeFullAccess policy works for me.

xvvvyz avatar Oct 03 '18 16:10 xvvvyz

@cadejscroggins even for the unuath role?

rayhaanq avatar Oct 03 '18 16:10 rayhaanq

@rayhaanq If you want to allow unauthenticated api calls, yes.

xvvvyz avatar Oct 03 '18 16:10 xvvvyz

@cadejscroggins ah wicked. Is it still possible to apply fine grained access control using the @auth directive?

rayhaanq avatar Oct 03 '18 16:10 rayhaanq

@rayhaanq for authenticated users it's pretty easy as you can add users to groups and give them specific permissions in @auth, but, as I mentioned above, I haven't figured out how to give unauthenticated users specific permissions.

Edit: I just realized that allow: unauthenticated should probably also apply to signed in users (other than owner) as well. Maybe something like "public" or "everyone" would work.

xvvvyz avatar Oct 03 '18 16:10 xvvvyz

For a clarification, the @auth directive currently supports Cognito User Pools only. In the future we will expand support for IAM and can do many of the same things but this needs to be worked on. As for the unauthenticated access, we have an issue https://github.com/aws-amplify/amplify-cli/issues/54 that is tracking this.

mikeparisstuff avatar Oct 09 '18 23:10 mikeparisstuff

I see. Thanks @mikeparisstuff.

the @auth directive currently supports Cognito User Pools only. In the future we will expand support for IAM and can do many of the same things but this needs to be worked on

Is there an issue somewhere for this as well, or maybe a roadmap?

xvvvyz avatar Oct 09 '18 23:10 xvvvyz

I think this could be done with Cognito Identity Pools, but I'm not sure if the currently generated resolvers are compatible.

blbradley avatar Nov 05 '18 02:11 blbradley

Comfirmed working with Cognito Identity Pools. I'll need to add some @auth to my app, now!

blbradley avatar Nov 05 '18 02:11 blbradley

@cadejscroggins @blbradley we are looking at doing this, but the key problem is that doing Fine Grained Access control might be limited since AWS credentials aren't the same as OIDC tokens from Cognito and therefore the $context.identity object which is available in a GraphQL resolver won't have a username for us to filter requests on in the same manner.

If we opened up @auth to allow for AWS IAM credentials what type of filtering would you expect here? Is coarse grained access acceptable meaning on IAM policies like so: https://docs.aws.amazon.com/appsync/latest/devguide/security.html#aws-iam-authorization

undefobj avatar Nov 05 '18 03:11 undefobj

@undefobj for my personal use case, I just need a way to have content that is read/write for the owner and read-only for everyone else (including unauthenticated users). It seems IAM auth should work great for that. Unless there's a standardized, non-hacky (read: creating a hardcoded Cognito user) way to allow anonymous requests that I missed, I think it's worth adding IAM to @auth.

Thoughts?

xvvvyz avatar Nov 08 '18 01:11 xvvvyz

UPDATE

This actual only handles the owner issue. I still can't see the records when I have no authenticated user :/


@cadejscroggins I have the same scenario:

I just need a way to have content that is read/write for the owner and read-only for everyone else (including unauthenticated users)

I just figured out how to do this via the AppSync interface. I'm going to note here in case it helps you and anybody else:

  1. Login to AppSync and navigate to Schema
  2. In the Resolvers panel, find the Query resolvers
  3. Click on the Resolver for the appropriate query (my case was for listOffers)
  4. Update the response mapping template, removing the authentication logic.

Mine was as simple as replacing the hand-built list with: $util.toJson($ctx.result)

image

image

I was then able to test the response using the AppSync Queries interface and just pasting in the same query that my app makes.

miwillhite avatar Nov 15 '18 18:11 miwillhite

Ok, the trick lies in Cognito's custom authentication option: https://aws-amplify.github.io/docs/js/authentication#customizing-authentication-flow

The API

Auth.signIn only requires the username param, so you can omit the password.

That configures your sign in to a CUSTOM_AUTH flow type: https://github.com/aws-amplify/amplify-js/blob/4644b432/packages/auth/src/Auth.ts#L416

Create a User

First you'll need to create a user in your Cognito User Pool…it just needs a username, nothing else. I called mine guest.

Create a Challenge

Then you have to set up some Lambda functions as Triggers in your User Pool.

I'm not sure how much of this is required, but if you don't define them then you get an error about null and Lambda)

These establish a series of challenge steps.

Specifically:

  1. Define Auth Challenge
  2. Create Auth Challenge
  3. Verify Auth Challenge

Disclaimer I'm still trying to figure these out, I just c&p'd from the Amplify docs and the author of this "optional password" patch: https://github.com/buggy/project-x-server/tree/master/shopify/src

Up to this point I haven't figured out how to define the challenge question (it's late, bed time 💤 ) so I ended up just setting the verifyAuthChallenge fn to true:

exports.handler = async (event, context) => {
  event.response.answerCorrect = true;
  event;
};

Finally I can call this:

(async () => {
  try {
    const user = await Auth.signIn ('guest');
    await Auth.sendCustomChallengeAnswer (user, 'foo');
    navigation.navigate ('App');
  } catch (err) {
    console.error (err);
  }
}) ();

I hope to get the actual challenge pieces figured out next week, but for now I have the desired effect of readonly models for non authorized users!


I hope this helps somebody! I'll continue to post as I figure out the rest of the challenge bits.

miwillhite avatar Nov 16 '18 05:11 miwillhite

I get GraphQLError: Request failed with status code 401

Now I have everything configured in aws-exports: aws_appsync_graphqlEndpoint aws_appsync_region aws_appsync_authenticationType set to AWS_IAM aws_appsync_apiKey "null" aws_project_region aws_cognito_identity_pool_id aws_cognito_region aws_user_pools_id aws_user_pools_web_client_id

Unauthenticated role has full access to AppSync GraphQL

What else could be missing?

mkrn avatar Nov 23 '18 14:11 mkrn

Any update on this? Is this going to be added to the '@auth' directive? I'd like to set up an API where everyone can read but only a specific group can create, update, delete.

thijsvdbb avatar Jan 11 '19 16:01 thijsvdbb

The frustration here for me is that @auth doesn't work for IAM, even for users who are authenticated in the application itself.

One thing I've accomplished on my own is creating a lambda that strips the "Cognito Sub" out of the IdentityProvider variable in the context.identity for IAM users. This can be resolved to a Cognito user via the AWS-SDK. Could a similar functionality be added to appsync + Amplify to enable @auth for logged in users on an IAM_AUTH stack?

sollipse avatar Jan 13 '19 19:01 sollipse