AppSync:使用AWS_IAM auth时在$ context中获取用户信息

时间:2018-04-29 10:36:27

标签: amazon-cloudformation amazon-cognito aws-appsync aws-amplify

在AppSync中,当您使用Cognito用户池作为身份验证设置您的身份时,您将获得

identity: 
   { sub: 'bcb5cd53-315a-40df-a41b-1db02a4c1bd9',
     issuer: 'https://cognito-idp.us-west-2.amazonaws.com/us-west-2_oicu812',
     username: 'skillet',
     claims: 
      { sub: 'bcb5cd53-315a-40df-a41b-1db02a4c1bd9',
        aud: '7re1oap5fhm3ngpje9r81vgpoe',
        email_verified: true,
        event_id: 'bb65ba5d-4689-11e8-bee7-2d0da8da81ab',
        token_use: 'id',
        auth_time: 1524441800,
        iss: 'https://cognito-idp.us-west-2.amazonaws.com/us-west-2_oicu812',
        'cognito:username': 'skillet',
        exp: 1524459387,
        iat: 1524455787,
        email: 'myemail@nope.com' },
     sourceIp: [ '11.222.33.200' ],
     defaultAuthStrategy: 'ALLOW',
     groups: null }

但是,当您使用AWS_IAM auth时,您将获得

identity:
{ accountId: '12121212121', //<--- my amazon account ID
  cognitoIdentityPoolId: 'us-west-2:39b1f3e4-330e-40f6-b738-266682302b59',
  cognitoIdentityId: 'us-west-2:a458498b-b1ac-46c1-9c5e-bf932bad0d95',
  sourceIp: [ '33.222.11.200' ],
  username: 'AROAJGBZT5A433EVW6O3Q:CognitoIdentityCredentials',
  userArn: 'arn:aws:sts::454227793445:assumed-role/MEMORYCARDS-CognitoAuthorizedRole-dev/CognitoIdentityCredentials',
  cognitoIdentityAuthType: 'authenticated',
  cognitoIdentityAuthProvider: '"cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob","cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob:CognitoSignIn:1a072f08-5c61-4c89-807e-417d22702eb7"' }

文档说这是预期的,https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html。 但是,如果您使用AWS_IAM连接到Cognito(需要具有未经身份验证的访问权限),您应该如何获得用户的用户名,电子邮件,子邮件等?使用AWS_IAM类型验证时,我需要访问用户的声明

4 个答案:

答案 0 :(得分:5)

要通过AppSync API访问用户的用户名,电子邮件,子邮件等,可以得到答案:https://stackoverflow.com/a/42405528/1207523

总结一下,您希望将用户池标识令牌发送到您的API(例如AppSync或API网关)。您的API请求已通过IAM身份验证。然后,您在Lambda函数中验证ID令牌,现在您已经验证了IAM用户和用户池数据。

您希望将IAM的identity.cognitoIdentityId用作您的用户表的主键。将ID令牌中包含的数据(用户名,电子邮件等)添加为属性。

通过这种方式,您可以通过API提供用户的声明。现在,例如,您可以将$ctx.identity.cognitoIdentityId设置为项目的所有者。然后,也许其他用户可以通过GraphQL解析器查看所有者的名称。

如果您需要在解析器中访问用户的声明,我担心目前似乎无法做到这一点。我对此提出了一个问题,因为它对授权很有帮助:Group authorization in AppSync using IAM authentication

在这种情况下,您可以使用Lambda作为数据源,而不是使用解析程序,并从上述用户表中检索用户的声明。

目前这有点困难:)

答案 1 :(得分:3)

这是错误的答案。我注意到cognitoIdentityAuthProvider: '"cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob","cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob:CognitoSignIn:1a072f08-5c61-4c89-807e-417d22702eb7"包含Cognito用户的子(CognitoSignIn之后的大)。您可以使用正则表达式提取,并使用aws-sdk从cognito用户池中获取用户的信息。

///////RETRIEVE THE AUTHENTICATED USER'S INFORMATION//////////
if(event.context.identity.cognitoIdentityAuthType === 'authenticated'){
    let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
    //Extract the user's sub (ID) from one of the context indentity fields
    //the REGEX in match looks for the strings btwn 'CognitoSignIn:' and '"', which represents the user sub
    let userSub = event.context.identity.cognitoIdentityAuthProvider.match(/CognitoSignIn:(.*?)"/)[1];
    let filter = 'sub = \"'+userSub+'\"'    // string with format = 'sub = \"1a072f08-5c61-4c89-807e-417d22702eb7\"'
    let usersData = await cognitoidentityserviceprovider.listUsers( {Filter:  filter, UserPoolId: "us-west-2_KsyTKrQ2M",Limit: 1}).promise()
    event.context.identity.user=usersData.Users[0]; 

}

这是一个错误的答案,因为您正在ping用户池数据库而不是仅解码JWT。

答案 2 :(得分:2)

这是我的答案。 appSync客户端库中存在一个错误,它会覆盖所有自定义标头。从那以后,这已得到修复。现在你可以传递自定义标题,这些标题将一直提供给你的解析器,我将它传递给我的lambda函数(再次注意,我使用的是lambda datasourcres而不是使用dynamoDB)。

所以我在客户端连接了我登录的JWT,在我的lambda函数的服务器端,我解码它。您需要由cognito创建的公钥来验证JWT。 (你不需要秘密密钥。)每个用户池都有一个“众所周知的密钥”网址,我第一次运行我的lambda时会ping,但就像我的mongoDB连接一样,它在lambda调用之间保持不变(至少有一段时间。)

这是lambda解析器......

const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
const request = require('request-promise-native');
const _ = require('lodash')

//ITEMS THAT SHOULD BE PERSISTED BETWEEN LAMBDA EXECUTIONS
let conn = null; //MONGODB CONNECTION
let pem = null;  //PROCESSED JWT PUBLIC KEY FOR OUR COGNITO USER POOL, SAME FOR EVERY USER

exports.graphqlHandler =  async (event, lambdaContext) => {
    // Make sure to add this so you can re-use `conn` between function calls.
    // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
    lambdaContext.callbackWaitsForEmptyEventLoop = false; 

    try{
        ////////////////// AUTHORIZATION/USER INFO /////////////////////////
        //ADD USER INFO, IF A LOGGED IN USER WITH VALID JWT MAKES THE REQUEST
        var token = _.get(event,'context.request.headers.jwt'); //equivalen to "token = event.context.re; quest.headers.alexauthorization;" but fails gracefully
        if(token){
            //GET THE ID OF THE PUBLIC KEY (KID) FROM THE TOKEN HEADER
            var decodedToken = jwt.decode(token, {complete: true});
            // GET THE PUBLIC KEY TO NEEDED TO VERIFY THE SIGNATURE (no private/secret key needed)
            if(!pem){ 
                await request({ //blocking, waits for public key if you don't already have it
                    uri:`https://cognito-idp.${process.env.REGION}.amazonaws.com/${process.env.USER_POOL_ID}/.well-known/jwks.json`,
                    resolveWithFullResponse: true //Otherwise only the responce body would be returned
                })
                    .then(function ( resp) {
                        if(resp.statusCode != 200){
                            throw new Error(resp.statusCode,`Request of JWT key with unexpected statusCode: expecting 200, received ${resp.statusCode}`);
                        }
                        let {body} = resp; //GET THE REPSONCE BODY
                        body = JSON.parse(body);  //body is a string, convert it to JSON
                        // body is an array of more than one JW keys.  User the key id in the JWT header to select the correct key object
                        var keyObject = _.find(body.keys,{"kid":decodedToken.header.kid});
                        pem = jwkToPem(keyObject);//convert jwk to pem
                    });
            }
            //VERIFY THE JWT SIGNATURE. IF THE SIGNATURE IS VALID, THEN ADD THE JWT TO THE IDENTITY OBJECT.
            jwt.verify(token, pem, function(error, decoded) {//not async
                if(error){
                    console.error(error);
                    throw new Error(401,error);
                }
                event.context.identity.user=decoded;
            });
        }
        return run(event)
    } catch (error) {//catch all errors and return them in an orderly manner
        console.error(error);
        throw new Error(error);
    }
};

//async/await keywords used for asynchronous calls to prevent lambda function from returning before mongodb interactions return
async function run(event) {
    // `conn` is in the global scope, Lambda may retain it between function calls thanks to `callbackWaitsForEmptyEventLoop`.
    if (conn == null) {
        //connect asyncoronously to mongodb
        conn = await mongoose.createConnection(process.env.MONGO_URL);
        //define the mongoose Schema
        let mySchema = new mongoose.Schema({ 
            ///my mongoose schem
        }); 
        mySchema('toJSON', { virtuals: true }); //will include both id and _id
        conn.model('mySchema', mySchema );  
    }
    //Get the mongoose Model from the Schema
    let mod = conn.model('mySchema');
    switch(event.field) {
        case "getOne": {
            return mod.findById(event.context.arguments.id);
        }   break;
        case "getAll": {
            return mod.find()
        }   break;
        default: {
            throw new Error ("Lambda handler error: Unknown field, unable to resolve " + event.field);
        }   break;
    }           
}

这比我的其他“坏”答案更好,因为您并不总是查询数据库以获取您在客户端已有的信息。我的经验快了大约3倍。

答案 3 :(得分:0)

如果您使用的是AWS Amplify,我要做的就是按照here的说明设置自定义标头username,就像这样:

Amplify.configure({
 API: {
   graphql_headers: async () => ({
    // 'My-Custom-Header': 'my value'
     username: 'myUsername'
   })
 }
});

然后在我的解析器中,我可以使用以下方式访问标头:

 $context.request.headers.username

如AppSync的文档here访问请求标头

部分中所述