我将Amplify用于Web应用程序(应用程序A),但我还有另一个node.js应用程序(应用程序B),我想使用它将一些数据写入DynamoDB表.应用程序B没有前端,因此,我需要应用程序B能够有一个未经授权的访问(或找到一种方法来验证在后端.

我做了以下工作:

  • 已初始化放大
  • 建立Cognito应用程序池
  • 已在Team-Provider-info.json中列出的unauth角色上配置各种策略
  • 已将取消身份验证角色附加到联合身份策略
  • 同时try 了AWS_APPSYNC_AUTHENTIONTYPE":"Amazon_Cognito_User_Pools"和"IAM"
  • 将模型上的身份验证规则设置为公共
  • RAN放大更新身份验证以设置未经身份验证的访问

然而,在Amplify CLI中和在AppSync控制台中使用查询时,我仍然收到错误"Not Authorated to Access ListPersonalInfos on type Query".

下面是我的身份验证解析器VTL和CloudWatch日志(log)

Auth Resolver VTL

## [Start] Authorization Steps. **
$util.qr($ctx.stash.put("hasAuth", true))
#set( $isAuthorized = false )
#set( $primaryFieldMap = {} )
#if( $util.authType() == "API Key Authorization" )

#end
#if( $util.authType() == "IAM Authorization" )
  #set( $adminRoles = ["ap-southeast-2_YNRFmtdr2_Full-access/CognitoIdentityCredentials","ap-southeast-2_YNRFmtdr2_Manage-only/CognitoIdentityCredentials"] )
  #foreach( $adminRole in $adminRoles )
    #if( $ctx.identity.userArn.contains($adminRole) && $ctx.identity.userArn != $ctx.stash.authRole && $ctx.identity.userArn != $ctx.stash.unauthRole )
      #return($util.toJson({}))
    #end
  #end
$util.unauthorized()
#end
#if( $util.authType() == "User Pool Authorization" )
  #if( !$isAuthorized )
    #set( $staticGroupRoles = [{"claim":"cognito:groups","entity":"GoThriveAdmin"}] )
    #foreach( $groupRole in $staticGroupRoles )
      #set( $groupsInToken = $util.defaultIfNull($ctx.identity.claims.get($groupRole.claim), []) )
      #if( $groupsInToken.contains($groupRole.entity) )
        #set( $isAuthorized = true )
        #break
      #end
    #end
  #end
  #if( !$isAuthorized )
    #set( $authFilter = [] )
    #set( $ownerClaim0 = $util.defaultIfNull($ctx.identity.claims.get("sub"), null) )
    #set( $currentClaim1 = $util.defaultIfNull($ctx.identity.claims.get("username"), $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), null)) )
    #if( !$util.isNull($ownerClaim0) && !$util.isNull($currentClaim1) )
      #set( $ownerClaim0 = "$ownerClaim0::$currentClaim1" )
      #if( !$util.isNull($ownerClaim0) )
        $util.qr($authFilter.add({"owner": { "eq": $ownerClaim0 }}))
      #end
    #end
    #set( $role0_0 = $util.defaultIfNull($ctx.identity.claims.get("sub"), null) )
    #if( !$util.isNull($role0_0) )
      $util.qr($authFilter.add({"owner": { "eq": $role0_0 }}))
    #end
    #set( $role0_1 = $util.defaultIfNull($ctx.identity.claims.get("username"), $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), null)) )
    #if( !$util.isNull($role0_1) )
      $util.qr($authFilter.add({"owner": { "eq": $role0_1 }}))
    #end
    #if( !$authFilter.isEmpty() )
      $util.qr($ctx.stash.put("authFilter", { "or": $authFilter }))
    #end
  #end
#end
#if( !$isAuthorized && $util.isNull($ctx.stash.authFilter) )
$util.unauthorized()
#end
$util.toJson({"version":"2018-05-29","payload":{}})
## [End] Authorization Steps. **

CloudWatch Logs

{
    "logType": "RequestMapping",
    "path": [
        "listPersonalInfos"
    ],
    "fieldName": "listPersonalInfos",
    "resolverArn": "arn:aws:appsync:ap-southeast-2:771661204178:apis/6pu5wf3wvfcr7dh3zribqhp6ua/types/Query/resolvers/listPersonalInfos",
    "functionName": "QuerygetPersonalInfoauth0Function",
    "requestId": "1817ebd7-80d3-48da-93d3-471f37aa665a",
    "context": {
        "arguments": {},
        "prev": {
            "result": {}
        },
        "stash": {
            "authRole": "arn:aws:sts::771661204178:assumed-role/amplify-talentui-dev-122653-authRole/CognitoIdentityCredentials",
            "conditions": [],
            "connectionAttributes": {},
            "fieldName": "listPersonalInfos",
            "hasAuth": true,
            "metadata": {
                "dataSourceType": "AMAZON_DYNAMODB",
                "apiId": "6pu5wf3wvfcr7dh3zribqhp6ua"
            },
            "tableName": "PersonalInfo-6pu5wf3wvfcr7dh3zribqhp6ua-dev",
            "typeName": "Query",
            "unauthRole": "arn:aws:sts::771661204178:assumed-role/amplify-talentui-dev-122653-unauthRole/CognitoIdentityCredentials"
        },
        "outErrors": []
    },
    "fieldInError": true,
    "errors": [
        "Not Authorized to access listPersonalInfos on type Query"
    ],
    "parentType": "Query",
    "graphQLAPIId": "6pu5wf3wvfcr7dh3zribqhp6ua",
    "functionArn": "arn:aws:appsync:ap-southeast-2:771661204178:apis/6pu5wf3wvfcr7dh3zribqhp6ua/functions/2zc46rgvzjgn3osvltkfuz4g3y"
}

推荐答案

我终于找到了问题所在.尽管我在Amplify和/或AppSync设置中设置了默认授权模式,并在我的模型中结合了公共的authRules指令,但这并不起作用.

以下是我为解决这个问题所做的:

  • 转到Amplify控制台
  • 从菜单中打开数据选项卡
  • 单击需要对其应用身份验证规则的模型
  • In the Model window that opens on the right, add the auth rules you need (see IMAGE1个 below for my example:
  • 保存并部署
  • 在您的Amplify CLI应用程序中运行amplify pull

IMAGE1

enter image description here

这在我的代码中创建了以下模型身份验证指令:

@model @auth(rules: [{allow: public, operations: [create, update, read]}, {allow: private, operations: [create, update, read], provider: iam}, {allow: owner}, {allow: private}])

我还将Auth.signIn()添加到我的代码中,并将GraphQL查询authMode设置为Amazon_Cognito_User_Pools,如下所示:

   try {
        await Auth.signIn(process.env.USERNAME, process.env.PASSWORD);
   } catch (error) {
        console.log('error signing in', error);
   }

   const result = await API.graphql<GraphQLQuery<ListPersonalInfosQuery>>({ 
       query: queries.listPersonalInfos,
       authMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS,
  }) as { data: ListPersonalInfosQuery; errors: any[] };

我现在可以从App B访问DynamoDB表.这不是使用未经身份验证的访问,但它起作用了.我相信有一种方法可以使用unauth方法访问,因为这是amplify add|update auth中的一个选项,并且默认情况下会创建unauth用户角色.如果有人能找到办法,我会很感兴趣的.

Node.js相关问答推荐

如何处理EPIPE时,使用axios并期待413响应?

CloudTasksClient在Firebase Function % s onDocumentCreated中实例化时导致错误

使用参考中断Mongoose模型-Node.js

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

我需要聚合两个 MongoDB 集合

$not 的聚合版本是什么?

多个 Axios 请求合并

表达限制资源属于特定用户的优雅方式

为什么 req.params.id 返回 undefined未定义?

当我们有esnext时,为什么我们需要nodenext typescript 编译器选项?

这到底是什么';拒绝未经授权';对我来说是什么意思?

npm 不会安装 express 吗?

ISODate 未定义

判断一个数组中的每个元素是否都在第二个数组中

如何使用 gulp-uglify 缩小 ES6 函数?

如何运行用 TypeScript 编写的 Mocha 测试?

我可以在 Heroku 中运行咖啡脚本吗?

用一级 try ... catch 捕获 JavaScript Promise 中的错误

在 react-router v4 中使用 React IndexRoute